xref: /linux/fs/ceph/mds_client.c (revision b43ab901d671e3e3cad425ea5e9a3c74e266dcdd)
1 #include <linux/ceph/ceph_debug.h>
2 
3 #include <linux/fs.h>
4 #include <linux/wait.h>
5 #include <linux/slab.h>
6 #include <linux/sched.h>
7 #include <linux/debugfs.h>
8 #include <linux/seq_file.h>
9 
10 #include "super.h"
11 #include "mds_client.h"
12 
13 #include <linux/ceph/messenger.h>
14 #include <linux/ceph/decode.h>
15 #include <linux/ceph/pagelist.h>
16 #include <linux/ceph/auth.h>
17 #include <linux/ceph/debugfs.h>
18 
19 /*
20  * A cluster of MDS (metadata server) daemons is responsible for
21  * managing the file system namespace (the directory hierarchy and
22  * inodes) and for coordinating shared access to storage.  Metadata is
23  * partitioning hierarchically across a number of servers, and that
24  * partition varies over time as the cluster adjusts the distribution
25  * in order to balance load.
26  *
27  * The MDS client is primarily responsible to managing synchronous
28  * metadata requests for operations like open, unlink, and so forth.
29  * If there is a MDS failure, we find out about it when we (possibly
30  * request and) receive a new MDS map, and can resubmit affected
31  * requests.
32  *
33  * For the most part, though, we take advantage of a lossless
34  * communications channel to the MDS, and do not need to worry about
35  * timing out or resubmitting requests.
36  *
37  * We maintain a stateful "session" with each MDS we interact with.
38  * Within each session, we sent periodic heartbeat messages to ensure
39  * any capabilities or leases we have been issues remain valid.  If
40  * the session times out and goes stale, our leases and capabilities
41  * are no longer valid.
42  */
43 
44 struct ceph_reconnect_state {
45 	struct ceph_pagelist *pagelist;
46 	bool flock;
47 };
48 
49 static void __wake_requests(struct ceph_mds_client *mdsc,
50 			    struct list_head *head);
51 
52 static const struct ceph_connection_operations mds_con_ops;
53 
54 
55 /*
56  * mds reply parsing
57  */
58 
59 /*
60  * parse individual inode info
61  */
62 static int parse_reply_info_in(void **p, void *end,
63 			       struct ceph_mds_reply_info_in *info,
64 			       int features)
65 {
66 	int err = -EIO;
67 
68 	info->in = *p;
69 	*p += sizeof(struct ceph_mds_reply_inode) +
70 		sizeof(*info->in->fragtree.splits) *
71 		le32_to_cpu(info->in->fragtree.nsplits);
72 
73 	ceph_decode_32_safe(p, end, info->symlink_len, bad);
74 	ceph_decode_need(p, end, info->symlink_len, bad);
75 	info->symlink = *p;
76 	*p += info->symlink_len;
77 
78 	if (features & CEPH_FEATURE_DIRLAYOUTHASH)
79 		ceph_decode_copy_safe(p, end, &info->dir_layout,
80 				      sizeof(info->dir_layout), bad);
81 	else
82 		memset(&info->dir_layout, 0, sizeof(info->dir_layout));
83 
84 	ceph_decode_32_safe(p, end, info->xattr_len, bad);
85 	ceph_decode_need(p, end, info->xattr_len, bad);
86 	info->xattr_data = *p;
87 	*p += info->xattr_len;
88 	return 0;
89 bad:
90 	return err;
91 }
92 
93 /*
94  * parse a normal reply, which may contain a (dir+)dentry and/or a
95  * target inode.
96  */
97 static int parse_reply_info_trace(void **p, void *end,
98 				  struct ceph_mds_reply_info_parsed *info,
99 				  int features)
100 {
101 	int err;
102 
103 	if (info->head->is_dentry) {
104 		err = parse_reply_info_in(p, end, &info->diri, features);
105 		if (err < 0)
106 			goto out_bad;
107 
108 		if (unlikely(*p + sizeof(*info->dirfrag) > end))
109 			goto bad;
110 		info->dirfrag = *p;
111 		*p += sizeof(*info->dirfrag) +
112 			sizeof(u32)*le32_to_cpu(info->dirfrag->ndist);
113 		if (unlikely(*p > end))
114 			goto bad;
115 
116 		ceph_decode_32_safe(p, end, info->dname_len, bad);
117 		ceph_decode_need(p, end, info->dname_len, bad);
118 		info->dname = *p;
119 		*p += info->dname_len;
120 		info->dlease = *p;
121 		*p += sizeof(*info->dlease);
122 	}
123 
124 	if (info->head->is_target) {
125 		err = parse_reply_info_in(p, end, &info->targeti, features);
126 		if (err < 0)
127 			goto out_bad;
128 	}
129 
130 	if (unlikely(*p != end))
131 		goto bad;
132 	return 0;
133 
134 bad:
135 	err = -EIO;
136 out_bad:
137 	pr_err("problem parsing mds trace %d\n", err);
138 	return err;
139 }
140 
141 /*
142  * parse readdir results
143  */
144 static int parse_reply_info_dir(void **p, void *end,
145 				struct ceph_mds_reply_info_parsed *info,
146 				int features)
147 {
148 	u32 num, i = 0;
149 	int err;
150 
151 	info->dir_dir = *p;
152 	if (*p + sizeof(*info->dir_dir) > end)
153 		goto bad;
154 	*p += sizeof(*info->dir_dir) +
155 		sizeof(u32)*le32_to_cpu(info->dir_dir->ndist);
156 	if (*p > end)
157 		goto bad;
158 
159 	ceph_decode_need(p, end, sizeof(num) + 2, bad);
160 	num = ceph_decode_32(p);
161 	info->dir_end = ceph_decode_8(p);
162 	info->dir_complete = ceph_decode_8(p);
163 	if (num == 0)
164 		goto done;
165 
166 	/* alloc large array */
167 	info->dir_nr = num;
168 	info->dir_in = kcalloc(num, sizeof(*info->dir_in) +
169 			       sizeof(*info->dir_dname) +
170 			       sizeof(*info->dir_dname_len) +
171 			       sizeof(*info->dir_dlease),
172 			       GFP_NOFS);
173 	if (info->dir_in == NULL) {
174 		err = -ENOMEM;
175 		goto out_bad;
176 	}
177 	info->dir_dname = (void *)(info->dir_in + num);
178 	info->dir_dname_len = (void *)(info->dir_dname + num);
179 	info->dir_dlease = (void *)(info->dir_dname_len + num);
180 
181 	while (num) {
182 		/* dentry */
183 		ceph_decode_need(p, end, sizeof(u32)*2, bad);
184 		info->dir_dname_len[i] = ceph_decode_32(p);
185 		ceph_decode_need(p, end, info->dir_dname_len[i], bad);
186 		info->dir_dname[i] = *p;
187 		*p += info->dir_dname_len[i];
188 		dout("parsed dir dname '%.*s'\n", info->dir_dname_len[i],
189 		     info->dir_dname[i]);
190 		info->dir_dlease[i] = *p;
191 		*p += sizeof(struct ceph_mds_reply_lease);
192 
193 		/* inode */
194 		err = parse_reply_info_in(p, end, &info->dir_in[i], features);
195 		if (err < 0)
196 			goto out_bad;
197 		i++;
198 		num--;
199 	}
200 
201 done:
202 	if (*p != end)
203 		goto bad;
204 	return 0;
205 
206 bad:
207 	err = -EIO;
208 out_bad:
209 	pr_err("problem parsing dir contents %d\n", err);
210 	return err;
211 }
212 
213 /*
214  * parse fcntl F_GETLK results
215  */
216 static int parse_reply_info_filelock(void **p, void *end,
217 				     struct ceph_mds_reply_info_parsed *info,
218 				     int features)
219 {
220 	if (*p + sizeof(*info->filelock_reply) > end)
221 		goto bad;
222 
223 	info->filelock_reply = *p;
224 	*p += sizeof(*info->filelock_reply);
225 
226 	if (unlikely(*p != end))
227 		goto bad;
228 	return 0;
229 
230 bad:
231 	return -EIO;
232 }
233 
234 /*
235  * parse extra results
236  */
237 static int parse_reply_info_extra(void **p, void *end,
238 				  struct ceph_mds_reply_info_parsed *info,
239 				  int features)
240 {
241 	if (info->head->op == CEPH_MDS_OP_GETFILELOCK)
242 		return parse_reply_info_filelock(p, end, info, features);
243 	else
244 		return parse_reply_info_dir(p, end, info, features);
245 }
246 
247 /*
248  * parse entire mds reply
249  */
250 static int parse_reply_info(struct ceph_msg *msg,
251 			    struct ceph_mds_reply_info_parsed *info,
252 			    int features)
253 {
254 	void *p, *end;
255 	u32 len;
256 	int err;
257 
258 	info->head = msg->front.iov_base;
259 	p = msg->front.iov_base + sizeof(struct ceph_mds_reply_head);
260 	end = p + msg->front.iov_len - sizeof(struct ceph_mds_reply_head);
261 
262 	/* trace */
263 	ceph_decode_32_safe(&p, end, len, bad);
264 	if (len > 0) {
265 		err = parse_reply_info_trace(&p, p+len, info, features);
266 		if (err < 0)
267 			goto out_bad;
268 	}
269 
270 	/* extra */
271 	ceph_decode_32_safe(&p, end, len, bad);
272 	if (len > 0) {
273 		err = parse_reply_info_extra(&p, p+len, info, features);
274 		if (err < 0)
275 			goto out_bad;
276 	}
277 
278 	/* snap blob */
279 	ceph_decode_32_safe(&p, end, len, bad);
280 	info->snapblob_len = len;
281 	info->snapblob = p;
282 	p += len;
283 
284 	if (p != end)
285 		goto bad;
286 	return 0;
287 
288 bad:
289 	err = -EIO;
290 out_bad:
291 	pr_err("mds parse_reply err %d\n", err);
292 	return err;
293 }
294 
295 static void destroy_reply_info(struct ceph_mds_reply_info_parsed *info)
296 {
297 	kfree(info->dir_in);
298 }
299 
300 
301 /*
302  * sessions
303  */
304 static const char *session_state_name(int s)
305 {
306 	switch (s) {
307 	case CEPH_MDS_SESSION_NEW: return "new";
308 	case CEPH_MDS_SESSION_OPENING: return "opening";
309 	case CEPH_MDS_SESSION_OPEN: return "open";
310 	case CEPH_MDS_SESSION_HUNG: return "hung";
311 	case CEPH_MDS_SESSION_CLOSING: return "closing";
312 	case CEPH_MDS_SESSION_RESTARTING: return "restarting";
313 	case CEPH_MDS_SESSION_RECONNECTING: return "reconnecting";
314 	default: return "???";
315 	}
316 }
317 
318 static struct ceph_mds_session *get_session(struct ceph_mds_session *s)
319 {
320 	if (atomic_inc_not_zero(&s->s_ref)) {
321 		dout("mdsc get_session %p %d -> %d\n", s,
322 		     atomic_read(&s->s_ref)-1, atomic_read(&s->s_ref));
323 		return s;
324 	} else {
325 		dout("mdsc get_session %p 0 -- FAIL", s);
326 		return NULL;
327 	}
328 }
329 
330 void ceph_put_mds_session(struct ceph_mds_session *s)
331 {
332 	dout("mdsc put_session %p %d -> %d\n", s,
333 	     atomic_read(&s->s_ref), atomic_read(&s->s_ref)-1);
334 	if (atomic_dec_and_test(&s->s_ref)) {
335 		if (s->s_authorizer)
336 		     s->s_mdsc->fsc->client->monc.auth->ops->destroy_authorizer(
337 			     s->s_mdsc->fsc->client->monc.auth,
338 			     s->s_authorizer);
339 		kfree(s);
340 	}
341 }
342 
343 /*
344  * called under mdsc->mutex
345  */
346 struct ceph_mds_session *__ceph_lookup_mds_session(struct ceph_mds_client *mdsc,
347 						   int mds)
348 {
349 	struct ceph_mds_session *session;
350 
351 	if (mds >= mdsc->max_sessions || mdsc->sessions[mds] == NULL)
352 		return NULL;
353 	session = mdsc->sessions[mds];
354 	dout("lookup_mds_session %p %d\n", session,
355 	     atomic_read(&session->s_ref));
356 	get_session(session);
357 	return session;
358 }
359 
360 static bool __have_session(struct ceph_mds_client *mdsc, int mds)
361 {
362 	if (mds >= mdsc->max_sessions)
363 		return false;
364 	return mdsc->sessions[mds];
365 }
366 
367 static int __verify_registered_session(struct ceph_mds_client *mdsc,
368 				       struct ceph_mds_session *s)
369 {
370 	if (s->s_mds >= mdsc->max_sessions ||
371 	    mdsc->sessions[s->s_mds] != s)
372 		return -ENOENT;
373 	return 0;
374 }
375 
376 /*
377  * create+register a new session for given mds.
378  * called under mdsc->mutex.
379  */
380 static struct ceph_mds_session *register_session(struct ceph_mds_client *mdsc,
381 						 int mds)
382 {
383 	struct ceph_mds_session *s;
384 
385 	s = kzalloc(sizeof(*s), GFP_NOFS);
386 	if (!s)
387 		return ERR_PTR(-ENOMEM);
388 	s->s_mdsc = mdsc;
389 	s->s_mds = mds;
390 	s->s_state = CEPH_MDS_SESSION_NEW;
391 	s->s_ttl = 0;
392 	s->s_seq = 0;
393 	mutex_init(&s->s_mutex);
394 
395 	ceph_con_init(mdsc->fsc->client->msgr, &s->s_con);
396 	s->s_con.private = s;
397 	s->s_con.ops = &mds_con_ops;
398 	s->s_con.peer_name.type = CEPH_ENTITY_TYPE_MDS;
399 	s->s_con.peer_name.num = cpu_to_le64(mds);
400 
401 	spin_lock_init(&s->s_cap_lock);
402 	s->s_cap_gen = 0;
403 	s->s_cap_ttl = 0;
404 	s->s_renew_requested = 0;
405 	s->s_renew_seq = 0;
406 	INIT_LIST_HEAD(&s->s_caps);
407 	s->s_nr_caps = 0;
408 	s->s_trim_caps = 0;
409 	atomic_set(&s->s_ref, 1);
410 	INIT_LIST_HEAD(&s->s_waiting);
411 	INIT_LIST_HEAD(&s->s_unsafe);
412 	s->s_num_cap_releases = 0;
413 	s->s_cap_iterator = NULL;
414 	INIT_LIST_HEAD(&s->s_cap_releases);
415 	INIT_LIST_HEAD(&s->s_cap_releases_done);
416 	INIT_LIST_HEAD(&s->s_cap_flushing);
417 	INIT_LIST_HEAD(&s->s_cap_snaps_flushing);
418 
419 	dout("register_session mds%d\n", mds);
420 	if (mds >= mdsc->max_sessions) {
421 		int newmax = 1 << get_count_order(mds+1);
422 		struct ceph_mds_session **sa;
423 
424 		dout("register_session realloc to %d\n", newmax);
425 		sa = kcalloc(newmax, sizeof(void *), GFP_NOFS);
426 		if (sa == NULL)
427 			goto fail_realloc;
428 		if (mdsc->sessions) {
429 			memcpy(sa, mdsc->sessions,
430 			       mdsc->max_sessions * sizeof(void *));
431 			kfree(mdsc->sessions);
432 		}
433 		mdsc->sessions = sa;
434 		mdsc->max_sessions = newmax;
435 	}
436 	mdsc->sessions[mds] = s;
437 	atomic_inc(&s->s_ref);  /* one ref to sessions[], one to caller */
438 
439 	ceph_con_open(&s->s_con, ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
440 
441 	return s;
442 
443 fail_realloc:
444 	kfree(s);
445 	return ERR_PTR(-ENOMEM);
446 }
447 
448 /*
449  * called under mdsc->mutex
450  */
451 static void __unregister_session(struct ceph_mds_client *mdsc,
452 			       struct ceph_mds_session *s)
453 {
454 	dout("__unregister_session mds%d %p\n", s->s_mds, s);
455 	BUG_ON(mdsc->sessions[s->s_mds] != s);
456 	mdsc->sessions[s->s_mds] = NULL;
457 	ceph_con_close(&s->s_con);
458 	ceph_put_mds_session(s);
459 }
460 
461 /*
462  * drop session refs in request.
463  *
464  * should be last request ref, or hold mdsc->mutex
465  */
466 static void put_request_session(struct ceph_mds_request *req)
467 {
468 	if (req->r_session) {
469 		ceph_put_mds_session(req->r_session);
470 		req->r_session = NULL;
471 	}
472 }
473 
474 void ceph_mdsc_release_request(struct kref *kref)
475 {
476 	struct ceph_mds_request *req = container_of(kref,
477 						    struct ceph_mds_request,
478 						    r_kref);
479 	if (req->r_request)
480 		ceph_msg_put(req->r_request);
481 	if (req->r_reply) {
482 		ceph_msg_put(req->r_reply);
483 		destroy_reply_info(&req->r_reply_info);
484 	}
485 	if (req->r_inode) {
486 		ceph_put_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
487 		iput(req->r_inode);
488 	}
489 	if (req->r_locked_dir)
490 		ceph_put_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
491 	if (req->r_target_inode)
492 		iput(req->r_target_inode);
493 	if (req->r_dentry)
494 		dput(req->r_dentry);
495 	if (req->r_old_dentry) {
496 		/*
497 		 * track (and drop pins for) r_old_dentry_dir
498 		 * separately, since r_old_dentry's d_parent may have
499 		 * changed between the dir mutex being dropped and
500 		 * this request being freed.
501 		 */
502 		ceph_put_cap_refs(ceph_inode(req->r_old_dentry_dir),
503 				  CEPH_CAP_PIN);
504 		dput(req->r_old_dentry);
505 		iput(req->r_old_dentry_dir);
506 	}
507 	kfree(req->r_path1);
508 	kfree(req->r_path2);
509 	put_request_session(req);
510 	ceph_unreserve_caps(req->r_mdsc, &req->r_caps_reservation);
511 	kfree(req);
512 }
513 
514 /*
515  * lookup session, bump ref if found.
516  *
517  * called under mdsc->mutex.
518  */
519 static struct ceph_mds_request *__lookup_request(struct ceph_mds_client *mdsc,
520 					     u64 tid)
521 {
522 	struct ceph_mds_request *req;
523 	struct rb_node *n = mdsc->request_tree.rb_node;
524 
525 	while (n) {
526 		req = rb_entry(n, struct ceph_mds_request, r_node);
527 		if (tid < req->r_tid)
528 			n = n->rb_left;
529 		else if (tid > req->r_tid)
530 			n = n->rb_right;
531 		else {
532 			ceph_mdsc_get_request(req);
533 			return req;
534 		}
535 	}
536 	return NULL;
537 }
538 
539 static void __insert_request(struct ceph_mds_client *mdsc,
540 			     struct ceph_mds_request *new)
541 {
542 	struct rb_node **p = &mdsc->request_tree.rb_node;
543 	struct rb_node *parent = NULL;
544 	struct ceph_mds_request *req = NULL;
545 
546 	while (*p) {
547 		parent = *p;
548 		req = rb_entry(parent, struct ceph_mds_request, r_node);
549 		if (new->r_tid < req->r_tid)
550 			p = &(*p)->rb_left;
551 		else if (new->r_tid > req->r_tid)
552 			p = &(*p)->rb_right;
553 		else
554 			BUG();
555 	}
556 
557 	rb_link_node(&new->r_node, parent, p);
558 	rb_insert_color(&new->r_node, &mdsc->request_tree);
559 }
560 
561 /*
562  * Register an in-flight request, and assign a tid.  Link to directory
563  * are modifying (if any).
564  *
565  * Called under mdsc->mutex.
566  */
567 static void __register_request(struct ceph_mds_client *mdsc,
568 			       struct ceph_mds_request *req,
569 			       struct inode *dir)
570 {
571 	req->r_tid = ++mdsc->last_tid;
572 	if (req->r_num_caps)
573 		ceph_reserve_caps(mdsc, &req->r_caps_reservation,
574 				  req->r_num_caps);
575 	dout("__register_request %p tid %lld\n", req, req->r_tid);
576 	ceph_mdsc_get_request(req);
577 	__insert_request(mdsc, req);
578 
579 	req->r_uid = current_fsuid();
580 	req->r_gid = current_fsgid();
581 
582 	if (dir) {
583 		struct ceph_inode_info *ci = ceph_inode(dir);
584 
585 		ihold(dir);
586 		spin_lock(&ci->i_unsafe_lock);
587 		req->r_unsafe_dir = dir;
588 		list_add_tail(&req->r_unsafe_dir_item, &ci->i_unsafe_dirops);
589 		spin_unlock(&ci->i_unsafe_lock);
590 	}
591 }
592 
593 static void __unregister_request(struct ceph_mds_client *mdsc,
594 				 struct ceph_mds_request *req)
595 {
596 	dout("__unregister_request %p tid %lld\n", req, req->r_tid);
597 	rb_erase(&req->r_node, &mdsc->request_tree);
598 	RB_CLEAR_NODE(&req->r_node);
599 
600 	if (req->r_unsafe_dir) {
601 		struct ceph_inode_info *ci = ceph_inode(req->r_unsafe_dir);
602 
603 		spin_lock(&ci->i_unsafe_lock);
604 		list_del_init(&req->r_unsafe_dir_item);
605 		spin_unlock(&ci->i_unsafe_lock);
606 
607 		iput(req->r_unsafe_dir);
608 		req->r_unsafe_dir = NULL;
609 	}
610 
611 	ceph_mdsc_put_request(req);
612 }
613 
614 /*
615  * Choose mds to send request to next.  If there is a hint set in the
616  * request (e.g., due to a prior forward hint from the mds), use that.
617  * Otherwise, consult frag tree and/or caps to identify the
618  * appropriate mds.  If all else fails, choose randomly.
619  *
620  * Called under mdsc->mutex.
621  */
622 static struct dentry *get_nonsnap_parent(struct dentry *dentry)
623 {
624 	/*
625 	 * we don't need to worry about protecting the d_parent access
626 	 * here because we never renaming inside the snapped namespace
627 	 * except to resplice to another snapdir, and either the old or new
628 	 * result is a valid result.
629 	 */
630 	while (!IS_ROOT(dentry) && ceph_snap(dentry->d_inode) != CEPH_NOSNAP)
631 		dentry = dentry->d_parent;
632 	return dentry;
633 }
634 
635 static int __choose_mds(struct ceph_mds_client *mdsc,
636 			struct ceph_mds_request *req)
637 {
638 	struct inode *inode;
639 	struct ceph_inode_info *ci;
640 	struct ceph_cap *cap;
641 	int mode = req->r_direct_mode;
642 	int mds = -1;
643 	u32 hash = req->r_direct_hash;
644 	bool is_hash = req->r_direct_is_hash;
645 
646 	/*
647 	 * is there a specific mds we should try?  ignore hint if we have
648 	 * no session and the mds is not up (active or recovering).
649 	 */
650 	if (req->r_resend_mds >= 0 &&
651 	    (__have_session(mdsc, req->r_resend_mds) ||
652 	     ceph_mdsmap_get_state(mdsc->mdsmap, req->r_resend_mds) > 0)) {
653 		dout("choose_mds using resend_mds mds%d\n",
654 		     req->r_resend_mds);
655 		return req->r_resend_mds;
656 	}
657 
658 	if (mode == USE_RANDOM_MDS)
659 		goto random;
660 
661 	inode = NULL;
662 	if (req->r_inode) {
663 		inode = req->r_inode;
664 	} else if (req->r_dentry) {
665 		/* ignore race with rename; old or new d_parent is okay */
666 		struct dentry *parent = req->r_dentry->d_parent;
667 		struct inode *dir = parent->d_inode;
668 
669 		if (dir->i_sb != mdsc->fsc->sb) {
670 			/* not this fs! */
671 			inode = req->r_dentry->d_inode;
672 		} else if (ceph_snap(dir) != CEPH_NOSNAP) {
673 			/* direct snapped/virtual snapdir requests
674 			 * based on parent dir inode */
675 			struct dentry *dn = get_nonsnap_parent(parent);
676 			inode = dn->d_inode;
677 			dout("__choose_mds using nonsnap parent %p\n", inode);
678 		} else if (req->r_dentry->d_inode) {
679 			/* dentry target */
680 			inode = req->r_dentry->d_inode;
681 		} else {
682 			/* dir + name */
683 			inode = dir;
684 			hash = ceph_dentry_hash(dir, req->r_dentry);
685 			is_hash = true;
686 		}
687 	}
688 
689 	dout("__choose_mds %p is_hash=%d (%d) mode %d\n", inode, (int)is_hash,
690 	     (int)hash, mode);
691 	if (!inode)
692 		goto random;
693 	ci = ceph_inode(inode);
694 
695 	if (is_hash && S_ISDIR(inode->i_mode)) {
696 		struct ceph_inode_frag frag;
697 		int found;
698 
699 		ceph_choose_frag(ci, hash, &frag, &found);
700 		if (found) {
701 			if (mode == USE_ANY_MDS && frag.ndist > 0) {
702 				u8 r;
703 
704 				/* choose a random replica */
705 				get_random_bytes(&r, 1);
706 				r %= frag.ndist;
707 				mds = frag.dist[r];
708 				dout("choose_mds %p %llx.%llx "
709 				     "frag %u mds%d (%d/%d)\n",
710 				     inode, ceph_vinop(inode),
711 				     frag.frag, mds,
712 				     (int)r, frag.ndist);
713 				if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
714 				    CEPH_MDS_STATE_ACTIVE)
715 					return mds;
716 			}
717 
718 			/* since this file/dir wasn't known to be
719 			 * replicated, then we want to look for the
720 			 * authoritative mds. */
721 			mode = USE_AUTH_MDS;
722 			if (frag.mds >= 0) {
723 				/* choose auth mds */
724 				mds = frag.mds;
725 				dout("choose_mds %p %llx.%llx "
726 				     "frag %u mds%d (auth)\n",
727 				     inode, ceph_vinop(inode), frag.frag, mds);
728 				if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
729 				    CEPH_MDS_STATE_ACTIVE)
730 					return mds;
731 			}
732 		}
733 	}
734 
735 	spin_lock(&ci->i_ceph_lock);
736 	cap = NULL;
737 	if (mode == USE_AUTH_MDS)
738 		cap = ci->i_auth_cap;
739 	if (!cap && !RB_EMPTY_ROOT(&ci->i_caps))
740 		cap = rb_entry(rb_first(&ci->i_caps), struct ceph_cap, ci_node);
741 	if (!cap) {
742 		spin_unlock(&ci->i_ceph_lock);
743 		goto random;
744 	}
745 	mds = cap->session->s_mds;
746 	dout("choose_mds %p %llx.%llx mds%d (%scap %p)\n",
747 	     inode, ceph_vinop(inode), mds,
748 	     cap == ci->i_auth_cap ? "auth " : "", cap);
749 	spin_unlock(&ci->i_ceph_lock);
750 	return mds;
751 
752 random:
753 	mds = ceph_mdsmap_get_random_mds(mdsc->mdsmap);
754 	dout("choose_mds chose random mds%d\n", mds);
755 	return mds;
756 }
757 
758 
759 /*
760  * session messages
761  */
762 static struct ceph_msg *create_session_msg(u32 op, u64 seq)
763 {
764 	struct ceph_msg *msg;
765 	struct ceph_mds_session_head *h;
766 
767 	msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h), GFP_NOFS,
768 			   false);
769 	if (!msg) {
770 		pr_err("create_session_msg ENOMEM creating msg\n");
771 		return NULL;
772 	}
773 	h = msg->front.iov_base;
774 	h->op = cpu_to_le32(op);
775 	h->seq = cpu_to_le64(seq);
776 	return msg;
777 }
778 
779 /*
780  * send session open request.
781  *
782  * called under mdsc->mutex
783  */
784 static int __open_session(struct ceph_mds_client *mdsc,
785 			  struct ceph_mds_session *session)
786 {
787 	struct ceph_msg *msg;
788 	int mstate;
789 	int mds = session->s_mds;
790 
791 	/* wait for mds to go active? */
792 	mstate = ceph_mdsmap_get_state(mdsc->mdsmap, mds);
793 	dout("open_session to mds%d (%s)\n", mds,
794 	     ceph_mds_state_name(mstate));
795 	session->s_state = CEPH_MDS_SESSION_OPENING;
796 	session->s_renew_requested = jiffies;
797 
798 	/* send connect message */
799 	msg = create_session_msg(CEPH_SESSION_REQUEST_OPEN, session->s_seq);
800 	if (!msg)
801 		return -ENOMEM;
802 	ceph_con_send(&session->s_con, msg);
803 	return 0;
804 }
805 
806 /*
807  * open sessions for any export targets for the given mds
808  *
809  * called under mdsc->mutex
810  */
811 static void __open_export_target_sessions(struct ceph_mds_client *mdsc,
812 					  struct ceph_mds_session *session)
813 {
814 	struct ceph_mds_info *mi;
815 	struct ceph_mds_session *ts;
816 	int i, mds = session->s_mds;
817 	int target;
818 
819 	if (mds >= mdsc->mdsmap->m_max_mds)
820 		return;
821 	mi = &mdsc->mdsmap->m_info[mds];
822 	dout("open_export_target_sessions for mds%d (%d targets)\n",
823 	     session->s_mds, mi->num_export_targets);
824 
825 	for (i = 0; i < mi->num_export_targets; i++) {
826 		target = mi->export_targets[i];
827 		ts = __ceph_lookup_mds_session(mdsc, target);
828 		if (!ts) {
829 			ts = register_session(mdsc, target);
830 			if (IS_ERR(ts))
831 				return;
832 		}
833 		if (session->s_state == CEPH_MDS_SESSION_NEW ||
834 		    session->s_state == CEPH_MDS_SESSION_CLOSING)
835 			__open_session(mdsc, session);
836 		else
837 			dout(" mds%d target mds%d %p is %s\n", session->s_mds,
838 			     i, ts, session_state_name(ts->s_state));
839 		ceph_put_mds_session(ts);
840 	}
841 }
842 
843 void ceph_mdsc_open_export_target_sessions(struct ceph_mds_client *mdsc,
844 					   struct ceph_mds_session *session)
845 {
846 	mutex_lock(&mdsc->mutex);
847 	__open_export_target_sessions(mdsc, session);
848 	mutex_unlock(&mdsc->mutex);
849 }
850 
851 /*
852  * session caps
853  */
854 
855 /*
856  * Free preallocated cap messages assigned to this session
857  */
858 static void cleanup_cap_releases(struct ceph_mds_session *session)
859 {
860 	struct ceph_msg *msg;
861 
862 	spin_lock(&session->s_cap_lock);
863 	while (!list_empty(&session->s_cap_releases)) {
864 		msg = list_first_entry(&session->s_cap_releases,
865 				       struct ceph_msg, list_head);
866 		list_del_init(&msg->list_head);
867 		ceph_msg_put(msg);
868 	}
869 	while (!list_empty(&session->s_cap_releases_done)) {
870 		msg = list_first_entry(&session->s_cap_releases_done,
871 				       struct ceph_msg, list_head);
872 		list_del_init(&msg->list_head);
873 		ceph_msg_put(msg);
874 	}
875 	spin_unlock(&session->s_cap_lock);
876 }
877 
878 /*
879  * Helper to safely iterate over all caps associated with a session, with
880  * special care taken to handle a racing __ceph_remove_cap().
881  *
882  * Caller must hold session s_mutex.
883  */
884 static int iterate_session_caps(struct ceph_mds_session *session,
885 				 int (*cb)(struct inode *, struct ceph_cap *,
886 					    void *), void *arg)
887 {
888 	struct list_head *p;
889 	struct ceph_cap *cap;
890 	struct inode *inode, *last_inode = NULL;
891 	struct ceph_cap *old_cap = NULL;
892 	int ret;
893 
894 	dout("iterate_session_caps %p mds%d\n", session, session->s_mds);
895 	spin_lock(&session->s_cap_lock);
896 	p = session->s_caps.next;
897 	while (p != &session->s_caps) {
898 		cap = list_entry(p, struct ceph_cap, session_caps);
899 		inode = igrab(&cap->ci->vfs_inode);
900 		if (!inode) {
901 			p = p->next;
902 			continue;
903 		}
904 		session->s_cap_iterator = cap;
905 		spin_unlock(&session->s_cap_lock);
906 
907 		if (last_inode) {
908 			iput(last_inode);
909 			last_inode = NULL;
910 		}
911 		if (old_cap) {
912 			ceph_put_cap(session->s_mdsc, old_cap);
913 			old_cap = NULL;
914 		}
915 
916 		ret = cb(inode, cap, arg);
917 		last_inode = inode;
918 
919 		spin_lock(&session->s_cap_lock);
920 		p = p->next;
921 		if (cap->ci == NULL) {
922 			dout("iterate_session_caps  finishing cap %p removal\n",
923 			     cap);
924 			BUG_ON(cap->session != session);
925 			list_del_init(&cap->session_caps);
926 			session->s_nr_caps--;
927 			cap->session = NULL;
928 			old_cap = cap;  /* put_cap it w/o locks held */
929 		}
930 		if (ret < 0)
931 			goto out;
932 	}
933 	ret = 0;
934 out:
935 	session->s_cap_iterator = NULL;
936 	spin_unlock(&session->s_cap_lock);
937 
938 	if (last_inode)
939 		iput(last_inode);
940 	if (old_cap)
941 		ceph_put_cap(session->s_mdsc, old_cap);
942 
943 	return ret;
944 }
945 
946 static int remove_session_caps_cb(struct inode *inode, struct ceph_cap *cap,
947 				  void *arg)
948 {
949 	struct ceph_inode_info *ci = ceph_inode(inode);
950 	int drop = 0;
951 
952 	dout("removing cap %p, ci is %p, inode is %p\n",
953 	     cap, ci, &ci->vfs_inode);
954 	spin_lock(&ci->i_ceph_lock);
955 	__ceph_remove_cap(cap);
956 	if (!__ceph_is_any_real_caps(ci)) {
957 		struct ceph_mds_client *mdsc =
958 			ceph_sb_to_client(inode->i_sb)->mdsc;
959 
960 		spin_lock(&mdsc->cap_dirty_lock);
961 		if (!list_empty(&ci->i_dirty_item)) {
962 			pr_info(" dropping dirty %s state for %p %lld\n",
963 				ceph_cap_string(ci->i_dirty_caps),
964 				inode, ceph_ino(inode));
965 			ci->i_dirty_caps = 0;
966 			list_del_init(&ci->i_dirty_item);
967 			drop = 1;
968 		}
969 		if (!list_empty(&ci->i_flushing_item)) {
970 			pr_info(" dropping dirty+flushing %s state for %p %lld\n",
971 				ceph_cap_string(ci->i_flushing_caps),
972 				inode, ceph_ino(inode));
973 			ci->i_flushing_caps = 0;
974 			list_del_init(&ci->i_flushing_item);
975 			mdsc->num_cap_flushing--;
976 			drop = 1;
977 		}
978 		if (drop && ci->i_wrbuffer_ref) {
979 			pr_info(" dropping dirty data for %p %lld\n",
980 				inode, ceph_ino(inode));
981 			ci->i_wrbuffer_ref = 0;
982 			ci->i_wrbuffer_ref_head = 0;
983 			drop++;
984 		}
985 		spin_unlock(&mdsc->cap_dirty_lock);
986 	}
987 	spin_unlock(&ci->i_ceph_lock);
988 	while (drop--)
989 		iput(inode);
990 	return 0;
991 }
992 
993 /*
994  * caller must hold session s_mutex
995  */
996 static void remove_session_caps(struct ceph_mds_session *session)
997 {
998 	dout("remove_session_caps on %p\n", session);
999 	iterate_session_caps(session, remove_session_caps_cb, NULL);
1000 	BUG_ON(session->s_nr_caps > 0);
1001 	BUG_ON(!list_empty(&session->s_cap_flushing));
1002 	cleanup_cap_releases(session);
1003 }
1004 
1005 /*
1006  * wake up any threads waiting on this session's caps.  if the cap is
1007  * old (didn't get renewed on the client reconnect), remove it now.
1008  *
1009  * caller must hold s_mutex.
1010  */
1011 static int wake_up_session_cb(struct inode *inode, struct ceph_cap *cap,
1012 			      void *arg)
1013 {
1014 	struct ceph_inode_info *ci = ceph_inode(inode);
1015 
1016 	wake_up_all(&ci->i_cap_wq);
1017 	if (arg) {
1018 		spin_lock(&ci->i_ceph_lock);
1019 		ci->i_wanted_max_size = 0;
1020 		ci->i_requested_max_size = 0;
1021 		spin_unlock(&ci->i_ceph_lock);
1022 	}
1023 	return 0;
1024 }
1025 
1026 static void wake_up_session_caps(struct ceph_mds_session *session,
1027 				 int reconnect)
1028 {
1029 	dout("wake_up_session_caps %p mds%d\n", session, session->s_mds);
1030 	iterate_session_caps(session, wake_up_session_cb,
1031 			     (void *)(unsigned long)reconnect);
1032 }
1033 
1034 /*
1035  * Send periodic message to MDS renewing all currently held caps.  The
1036  * ack will reset the expiration for all caps from this session.
1037  *
1038  * caller holds s_mutex
1039  */
1040 static int send_renew_caps(struct ceph_mds_client *mdsc,
1041 			   struct ceph_mds_session *session)
1042 {
1043 	struct ceph_msg *msg;
1044 	int state;
1045 
1046 	if (time_after_eq(jiffies, session->s_cap_ttl) &&
1047 	    time_after_eq(session->s_cap_ttl, session->s_renew_requested))
1048 		pr_info("mds%d caps stale\n", session->s_mds);
1049 	session->s_renew_requested = jiffies;
1050 
1051 	/* do not try to renew caps until a recovering mds has reconnected
1052 	 * with its clients. */
1053 	state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
1054 	if (state < CEPH_MDS_STATE_RECONNECT) {
1055 		dout("send_renew_caps ignoring mds%d (%s)\n",
1056 		     session->s_mds, ceph_mds_state_name(state));
1057 		return 0;
1058 	}
1059 
1060 	dout("send_renew_caps to mds%d (%s)\n", session->s_mds,
1061 		ceph_mds_state_name(state));
1062 	msg = create_session_msg(CEPH_SESSION_REQUEST_RENEWCAPS,
1063 				 ++session->s_renew_seq);
1064 	if (!msg)
1065 		return -ENOMEM;
1066 	ceph_con_send(&session->s_con, msg);
1067 	return 0;
1068 }
1069 
1070 /*
1071  * Note new cap ttl, and any transition from stale -> not stale (fresh?).
1072  *
1073  * Called under session->s_mutex
1074  */
1075 static void renewed_caps(struct ceph_mds_client *mdsc,
1076 			 struct ceph_mds_session *session, int is_renew)
1077 {
1078 	int was_stale;
1079 	int wake = 0;
1080 
1081 	spin_lock(&session->s_cap_lock);
1082 	was_stale = is_renew && (session->s_cap_ttl == 0 ||
1083 				 time_after_eq(jiffies, session->s_cap_ttl));
1084 
1085 	session->s_cap_ttl = session->s_renew_requested +
1086 		mdsc->mdsmap->m_session_timeout*HZ;
1087 
1088 	if (was_stale) {
1089 		if (time_before(jiffies, session->s_cap_ttl)) {
1090 			pr_info("mds%d caps renewed\n", session->s_mds);
1091 			wake = 1;
1092 		} else {
1093 			pr_info("mds%d caps still stale\n", session->s_mds);
1094 		}
1095 	}
1096 	dout("renewed_caps mds%d ttl now %lu, was %s, now %s\n",
1097 	     session->s_mds, session->s_cap_ttl, was_stale ? "stale" : "fresh",
1098 	     time_before(jiffies, session->s_cap_ttl) ? "stale" : "fresh");
1099 	spin_unlock(&session->s_cap_lock);
1100 
1101 	if (wake)
1102 		wake_up_session_caps(session, 0);
1103 }
1104 
1105 /*
1106  * send a session close request
1107  */
1108 static int request_close_session(struct ceph_mds_client *mdsc,
1109 				 struct ceph_mds_session *session)
1110 {
1111 	struct ceph_msg *msg;
1112 
1113 	dout("request_close_session mds%d state %s seq %lld\n",
1114 	     session->s_mds, session_state_name(session->s_state),
1115 	     session->s_seq);
1116 	msg = create_session_msg(CEPH_SESSION_REQUEST_CLOSE, session->s_seq);
1117 	if (!msg)
1118 		return -ENOMEM;
1119 	ceph_con_send(&session->s_con, msg);
1120 	return 0;
1121 }
1122 
1123 /*
1124  * Called with s_mutex held.
1125  */
1126 static int __close_session(struct ceph_mds_client *mdsc,
1127 			 struct ceph_mds_session *session)
1128 {
1129 	if (session->s_state >= CEPH_MDS_SESSION_CLOSING)
1130 		return 0;
1131 	session->s_state = CEPH_MDS_SESSION_CLOSING;
1132 	return request_close_session(mdsc, session);
1133 }
1134 
1135 /*
1136  * Trim old(er) caps.
1137  *
1138  * Because we can't cache an inode without one or more caps, we do
1139  * this indirectly: if a cap is unused, we prune its aliases, at which
1140  * point the inode will hopefully get dropped to.
1141  *
1142  * Yes, this is a bit sloppy.  Our only real goal here is to respond to
1143  * memory pressure from the MDS, though, so it needn't be perfect.
1144  */
1145 static int trim_caps_cb(struct inode *inode, struct ceph_cap *cap, void *arg)
1146 {
1147 	struct ceph_mds_session *session = arg;
1148 	struct ceph_inode_info *ci = ceph_inode(inode);
1149 	int used, oissued, mine;
1150 
1151 	if (session->s_trim_caps <= 0)
1152 		return -1;
1153 
1154 	spin_lock(&ci->i_ceph_lock);
1155 	mine = cap->issued | cap->implemented;
1156 	used = __ceph_caps_used(ci);
1157 	oissued = __ceph_caps_issued_other(ci, cap);
1158 
1159 	dout("trim_caps_cb %p cap %p mine %s oissued %s used %s\n",
1160 	     inode, cap, ceph_cap_string(mine), ceph_cap_string(oissued),
1161 	     ceph_cap_string(used));
1162 	if (ci->i_dirty_caps)
1163 		goto out;   /* dirty caps */
1164 	if ((used & ~oissued) & mine)
1165 		goto out;   /* we need these caps */
1166 
1167 	session->s_trim_caps--;
1168 	if (oissued) {
1169 		/* we aren't the only cap.. just remove us */
1170 		__ceph_remove_cap(cap);
1171 	} else {
1172 		/* try to drop referring dentries */
1173 		spin_unlock(&ci->i_ceph_lock);
1174 		d_prune_aliases(inode);
1175 		dout("trim_caps_cb %p cap %p  pruned, count now %d\n",
1176 		     inode, cap, atomic_read(&inode->i_count));
1177 		return 0;
1178 	}
1179 
1180 out:
1181 	spin_unlock(&ci->i_ceph_lock);
1182 	return 0;
1183 }
1184 
1185 /*
1186  * Trim session cap count down to some max number.
1187  */
1188 static int trim_caps(struct ceph_mds_client *mdsc,
1189 		     struct ceph_mds_session *session,
1190 		     int max_caps)
1191 {
1192 	int trim_caps = session->s_nr_caps - max_caps;
1193 
1194 	dout("trim_caps mds%d start: %d / %d, trim %d\n",
1195 	     session->s_mds, session->s_nr_caps, max_caps, trim_caps);
1196 	if (trim_caps > 0) {
1197 		session->s_trim_caps = trim_caps;
1198 		iterate_session_caps(session, trim_caps_cb, session);
1199 		dout("trim_caps mds%d done: %d / %d, trimmed %d\n",
1200 		     session->s_mds, session->s_nr_caps, max_caps,
1201 			trim_caps - session->s_trim_caps);
1202 		session->s_trim_caps = 0;
1203 	}
1204 	return 0;
1205 }
1206 
1207 /*
1208  * Allocate cap_release messages.  If there is a partially full message
1209  * in the queue, try to allocate enough to cover it's remainder, so that
1210  * we can send it immediately.
1211  *
1212  * Called under s_mutex.
1213  */
1214 int ceph_add_cap_releases(struct ceph_mds_client *mdsc,
1215 			  struct ceph_mds_session *session)
1216 {
1217 	struct ceph_msg *msg, *partial = NULL;
1218 	struct ceph_mds_cap_release *head;
1219 	int err = -ENOMEM;
1220 	int extra = mdsc->fsc->mount_options->cap_release_safety;
1221 	int num;
1222 
1223 	dout("add_cap_releases %p mds%d extra %d\n", session, session->s_mds,
1224 	     extra);
1225 
1226 	spin_lock(&session->s_cap_lock);
1227 
1228 	if (!list_empty(&session->s_cap_releases)) {
1229 		msg = list_first_entry(&session->s_cap_releases,
1230 				       struct ceph_msg,
1231 				 list_head);
1232 		head = msg->front.iov_base;
1233 		num = le32_to_cpu(head->num);
1234 		if (num) {
1235 			dout(" partial %p with (%d/%d)\n", msg, num,
1236 			     (int)CEPH_CAPS_PER_RELEASE);
1237 			extra += CEPH_CAPS_PER_RELEASE - num;
1238 			partial = msg;
1239 		}
1240 	}
1241 	while (session->s_num_cap_releases < session->s_nr_caps + extra) {
1242 		spin_unlock(&session->s_cap_lock);
1243 		msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPRELEASE, PAGE_CACHE_SIZE,
1244 				   GFP_NOFS, false);
1245 		if (!msg)
1246 			goto out_unlocked;
1247 		dout("add_cap_releases %p msg %p now %d\n", session, msg,
1248 		     (int)msg->front.iov_len);
1249 		head = msg->front.iov_base;
1250 		head->num = cpu_to_le32(0);
1251 		msg->front.iov_len = sizeof(*head);
1252 		spin_lock(&session->s_cap_lock);
1253 		list_add(&msg->list_head, &session->s_cap_releases);
1254 		session->s_num_cap_releases += CEPH_CAPS_PER_RELEASE;
1255 	}
1256 
1257 	if (partial) {
1258 		head = partial->front.iov_base;
1259 		num = le32_to_cpu(head->num);
1260 		dout(" queueing partial %p with %d/%d\n", partial, num,
1261 		     (int)CEPH_CAPS_PER_RELEASE);
1262 		list_move_tail(&partial->list_head,
1263 			       &session->s_cap_releases_done);
1264 		session->s_num_cap_releases -= CEPH_CAPS_PER_RELEASE - num;
1265 	}
1266 	err = 0;
1267 	spin_unlock(&session->s_cap_lock);
1268 out_unlocked:
1269 	return err;
1270 }
1271 
1272 /*
1273  * flush all dirty inode data to disk.
1274  *
1275  * returns true if we've flushed through want_flush_seq
1276  */
1277 static int check_cap_flush(struct ceph_mds_client *mdsc, u64 want_flush_seq)
1278 {
1279 	int mds, ret = 1;
1280 
1281 	dout("check_cap_flush want %lld\n", want_flush_seq);
1282 	mutex_lock(&mdsc->mutex);
1283 	for (mds = 0; ret && mds < mdsc->max_sessions; mds++) {
1284 		struct ceph_mds_session *session = mdsc->sessions[mds];
1285 
1286 		if (!session)
1287 			continue;
1288 		get_session(session);
1289 		mutex_unlock(&mdsc->mutex);
1290 
1291 		mutex_lock(&session->s_mutex);
1292 		if (!list_empty(&session->s_cap_flushing)) {
1293 			struct ceph_inode_info *ci =
1294 				list_entry(session->s_cap_flushing.next,
1295 					   struct ceph_inode_info,
1296 					   i_flushing_item);
1297 			struct inode *inode = &ci->vfs_inode;
1298 
1299 			spin_lock(&ci->i_ceph_lock);
1300 			if (ci->i_cap_flush_seq <= want_flush_seq) {
1301 				dout("check_cap_flush still flushing %p "
1302 				     "seq %lld <= %lld to mds%d\n", inode,
1303 				     ci->i_cap_flush_seq, want_flush_seq,
1304 				     session->s_mds);
1305 				ret = 0;
1306 			}
1307 			spin_unlock(&ci->i_ceph_lock);
1308 		}
1309 		mutex_unlock(&session->s_mutex);
1310 		ceph_put_mds_session(session);
1311 
1312 		if (!ret)
1313 			return ret;
1314 		mutex_lock(&mdsc->mutex);
1315 	}
1316 
1317 	mutex_unlock(&mdsc->mutex);
1318 	dout("check_cap_flush ok, flushed thru %lld\n", want_flush_seq);
1319 	return ret;
1320 }
1321 
1322 /*
1323  * called under s_mutex
1324  */
1325 void ceph_send_cap_releases(struct ceph_mds_client *mdsc,
1326 			    struct ceph_mds_session *session)
1327 {
1328 	struct ceph_msg *msg;
1329 
1330 	dout("send_cap_releases mds%d\n", session->s_mds);
1331 	spin_lock(&session->s_cap_lock);
1332 	while (!list_empty(&session->s_cap_releases_done)) {
1333 		msg = list_first_entry(&session->s_cap_releases_done,
1334 				 struct ceph_msg, list_head);
1335 		list_del_init(&msg->list_head);
1336 		spin_unlock(&session->s_cap_lock);
1337 		msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1338 		dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1339 		ceph_con_send(&session->s_con, msg);
1340 		spin_lock(&session->s_cap_lock);
1341 	}
1342 	spin_unlock(&session->s_cap_lock);
1343 }
1344 
1345 static void discard_cap_releases(struct ceph_mds_client *mdsc,
1346 				 struct ceph_mds_session *session)
1347 {
1348 	struct ceph_msg *msg;
1349 	struct ceph_mds_cap_release *head;
1350 	unsigned num;
1351 
1352 	dout("discard_cap_releases mds%d\n", session->s_mds);
1353 	spin_lock(&session->s_cap_lock);
1354 
1355 	/* zero out the in-progress message */
1356 	msg = list_first_entry(&session->s_cap_releases,
1357 			       struct ceph_msg, list_head);
1358 	head = msg->front.iov_base;
1359 	num = le32_to_cpu(head->num);
1360 	dout("discard_cap_releases mds%d %p %u\n", session->s_mds, msg, num);
1361 	head->num = cpu_to_le32(0);
1362 	session->s_num_cap_releases += num;
1363 
1364 	/* requeue completed messages */
1365 	while (!list_empty(&session->s_cap_releases_done)) {
1366 		msg = list_first_entry(&session->s_cap_releases_done,
1367 				 struct ceph_msg, list_head);
1368 		list_del_init(&msg->list_head);
1369 
1370 		head = msg->front.iov_base;
1371 		num = le32_to_cpu(head->num);
1372 		dout("discard_cap_releases mds%d %p %u\n", session->s_mds, msg,
1373 		     num);
1374 		session->s_num_cap_releases += num;
1375 		head->num = cpu_to_le32(0);
1376 		msg->front.iov_len = sizeof(*head);
1377 		list_add(&msg->list_head, &session->s_cap_releases);
1378 	}
1379 
1380 	spin_unlock(&session->s_cap_lock);
1381 }
1382 
1383 /*
1384  * requests
1385  */
1386 
1387 /*
1388  * Create an mds request.
1389  */
1390 struct ceph_mds_request *
1391 ceph_mdsc_create_request(struct ceph_mds_client *mdsc, int op, int mode)
1392 {
1393 	struct ceph_mds_request *req = kzalloc(sizeof(*req), GFP_NOFS);
1394 
1395 	if (!req)
1396 		return ERR_PTR(-ENOMEM);
1397 
1398 	mutex_init(&req->r_fill_mutex);
1399 	req->r_mdsc = mdsc;
1400 	req->r_started = jiffies;
1401 	req->r_resend_mds = -1;
1402 	INIT_LIST_HEAD(&req->r_unsafe_dir_item);
1403 	req->r_fmode = -1;
1404 	kref_init(&req->r_kref);
1405 	INIT_LIST_HEAD(&req->r_wait);
1406 	init_completion(&req->r_completion);
1407 	init_completion(&req->r_safe_completion);
1408 	INIT_LIST_HEAD(&req->r_unsafe_item);
1409 
1410 	req->r_op = op;
1411 	req->r_direct_mode = mode;
1412 	return req;
1413 }
1414 
1415 /*
1416  * return oldest (lowest) request, tid in request tree, 0 if none.
1417  *
1418  * called under mdsc->mutex.
1419  */
1420 static struct ceph_mds_request *__get_oldest_req(struct ceph_mds_client *mdsc)
1421 {
1422 	if (RB_EMPTY_ROOT(&mdsc->request_tree))
1423 		return NULL;
1424 	return rb_entry(rb_first(&mdsc->request_tree),
1425 			struct ceph_mds_request, r_node);
1426 }
1427 
1428 static u64 __get_oldest_tid(struct ceph_mds_client *mdsc)
1429 {
1430 	struct ceph_mds_request *req = __get_oldest_req(mdsc);
1431 
1432 	if (req)
1433 		return req->r_tid;
1434 	return 0;
1435 }
1436 
1437 /*
1438  * Build a dentry's path.  Allocate on heap; caller must kfree.  Based
1439  * on build_path_from_dentry in fs/cifs/dir.c.
1440  *
1441  * If @stop_on_nosnap, generate path relative to the first non-snapped
1442  * inode.
1443  *
1444  * Encode hidden .snap dirs as a double /, i.e.
1445  *   foo/.snap/bar -> foo//bar
1446  */
1447 char *ceph_mdsc_build_path(struct dentry *dentry, int *plen, u64 *base,
1448 			   int stop_on_nosnap)
1449 {
1450 	struct dentry *temp;
1451 	char *path;
1452 	int len, pos;
1453 	unsigned seq;
1454 
1455 	if (dentry == NULL)
1456 		return ERR_PTR(-EINVAL);
1457 
1458 retry:
1459 	len = 0;
1460 	seq = read_seqbegin(&rename_lock);
1461 	rcu_read_lock();
1462 	for (temp = dentry; !IS_ROOT(temp);) {
1463 		struct inode *inode = temp->d_inode;
1464 		if (inode && ceph_snap(inode) == CEPH_SNAPDIR)
1465 			len++;  /* slash only */
1466 		else if (stop_on_nosnap && inode &&
1467 			 ceph_snap(inode) == CEPH_NOSNAP)
1468 			break;
1469 		else
1470 			len += 1 + temp->d_name.len;
1471 		temp = temp->d_parent;
1472 		if (temp == NULL) {
1473 			rcu_read_unlock();
1474 			pr_err("build_path corrupt dentry %p\n", dentry);
1475 			return ERR_PTR(-EINVAL);
1476 		}
1477 	}
1478 	rcu_read_unlock();
1479 	if (len)
1480 		len--;  /* no leading '/' */
1481 
1482 	path = kmalloc(len+1, GFP_NOFS);
1483 	if (path == NULL)
1484 		return ERR_PTR(-ENOMEM);
1485 	pos = len;
1486 	path[pos] = 0;	/* trailing null */
1487 	rcu_read_lock();
1488 	for (temp = dentry; !IS_ROOT(temp) && pos != 0; ) {
1489 		struct inode *inode;
1490 
1491 		spin_lock(&temp->d_lock);
1492 		inode = temp->d_inode;
1493 		if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
1494 			dout("build_path path+%d: %p SNAPDIR\n",
1495 			     pos, temp);
1496 		} else if (stop_on_nosnap && inode &&
1497 			   ceph_snap(inode) == CEPH_NOSNAP) {
1498 			spin_unlock(&temp->d_lock);
1499 			break;
1500 		} else {
1501 			pos -= temp->d_name.len;
1502 			if (pos < 0) {
1503 				spin_unlock(&temp->d_lock);
1504 				break;
1505 			}
1506 			strncpy(path + pos, temp->d_name.name,
1507 				temp->d_name.len);
1508 		}
1509 		spin_unlock(&temp->d_lock);
1510 		if (pos)
1511 			path[--pos] = '/';
1512 		temp = temp->d_parent;
1513 		if (temp == NULL) {
1514 			rcu_read_unlock();
1515 			pr_err("build_path corrupt dentry\n");
1516 			kfree(path);
1517 			return ERR_PTR(-EINVAL);
1518 		}
1519 	}
1520 	rcu_read_unlock();
1521 	if (pos != 0 || read_seqretry(&rename_lock, seq)) {
1522 		pr_err("build_path did not end path lookup where "
1523 		       "expected, namelen is %d, pos is %d\n", len, pos);
1524 		/* presumably this is only possible if racing with a
1525 		   rename of one of the parent directories (we can not
1526 		   lock the dentries above us to prevent this, but
1527 		   retrying should be harmless) */
1528 		kfree(path);
1529 		goto retry;
1530 	}
1531 
1532 	*base = ceph_ino(temp->d_inode);
1533 	*plen = len;
1534 	dout("build_path on %p %d built %llx '%.*s'\n",
1535 	     dentry, dentry->d_count, *base, len, path);
1536 	return path;
1537 }
1538 
1539 static int build_dentry_path(struct dentry *dentry,
1540 			     const char **ppath, int *ppathlen, u64 *pino,
1541 			     int *pfreepath)
1542 {
1543 	char *path;
1544 
1545 	if (ceph_snap(dentry->d_parent->d_inode) == CEPH_NOSNAP) {
1546 		*pino = ceph_ino(dentry->d_parent->d_inode);
1547 		*ppath = dentry->d_name.name;
1548 		*ppathlen = dentry->d_name.len;
1549 		return 0;
1550 	}
1551 	path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1552 	if (IS_ERR(path))
1553 		return PTR_ERR(path);
1554 	*ppath = path;
1555 	*pfreepath = 1;
1556 	return 0;
1557 }
1558 
1559 static int build_inode_path(struct inode *inode,
1560 			    const char **ppath, int *ppathlen, u64 *pino,
1561 			    int *pfreepath)
1562 {
1563 	struct dentry *dentry;
1564 	char *path;
1565 
1566 	if (ceph_snap(inode) == CEPH_NOSNAP) {
1567 		*pino = ceph_ino(inode);
1568 		*ppathlen = 0;
1569 		return 0;
1570 	}
1571 	dentry = d_find_alias(inode);
1572 	path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1573 	dput(dentry);
1574 	if (IS_ERR(path))
1575 		return PTR_ERR(path);
1576 	*ppath = path;
1577 	*pfreepath = 1;
1578 	return 0;
1579 }
1580 
1581 /*
1582  * request arguments may be specified via an inode *, a dentry *, or
1583  * an explicit ino+path.
1584  */
1585 static int set_request_path_attr(struct inode *rinode, struct dentry *rdentry,
1586 				  const char *rpath, u64 rino,
1587 				  const char **ppath, int *pathlen,
1588 				  u64 *ino, int *freepath)
1589 {
1590 	int r = 0;
1591 
1592 	if (rinode) {
1593 		r = build_inode_path(rinode, ppath, pathlen, ino, freepath);
1594 		dout(" inode %p %llx.%llx\n", rinode, ceph_ino(rinode),
1595 		     ceph_snap(rinode));
1596 	} else if (rdentry) {
1597 		r = build_dentry_path(rdentry, ppath, pathlen, ino, freepath);
1598 		dout(" dentry %p %llx/%.*s\n", rdentry, *ino, *pathlen,
1599 		     *ppath);
1600 	} else if (rpath || rino) {
1601 		*ino = rino;
1602 		*ppath = rpath;
1603 		*pathlen = strlen(rpath);
1604 		dout(" path %.*s\n", *pathlen, rpath);
1605 	}
1606 
1607 	return r;
1608 }
1609 
1610 /*
1611  * called under mdsc->mutex
1612  */
1613 static struct ceph_msg *create_request_message(struct ceph_mds_client *mdsc,
1614 					       struct ceph_mds_request *req,
1615 					       int mds)
1616 {
1617 	struct ceph_msg *msg;
1618 	struct ceph_mds_request_head *head;
1619 	const char *path1 = NULL;
1620 	const char *path2 = NULL;
1621 	u64 ino1 = 0, ino2 = 0;
1622 	int pathlen1 = 0, pathlen2 = 0;
1623 	int freepath1 = 0, freepath2 = 0;
1624 	int len;
1625 	u16 releases;
1626 	void *p, *end;
1627 	int ret;
1628 
1629 	ret = set_request_path_attr(req->r_inode, req->r_dentry,
1630 			      req->r_path1, req->r_ino1.ino,
1631 			      &path1, &pathlen1, &ino1, &freepath1);
1632 	if (ret < 0) {
1633 		msg = ERR_PTR(ret);
1634 		goto out;
1635 	}
1636 
1637 	ret = set_request_path_attr(NULL, req->r_old_dentry,
1638 			      req->r_path2, req->r_ino2.ino,
1639 			      &path2, &pathlen2, &ino2, &freepath2);
1640 	if (ret < 0) {
1641 		msg = ERR_PTR(ret);
1642 		goto out_free1;
1643 	}
1644 
1645 	len = sizeof(*head) +
1646 		pathlen1 + pathlen2 + 2*(1 + sizeof(u32) + sizeof(u64));
1647 
1648 	/* calculate (max) length for cap releases */
1649 	len += sizeof(struct ceph_mds_request_release) *
1650 		(!!req->r_inode_drop + !!req->r_dentry_drop +
1651 		 !!req->r_old_inode_drop + !!req->r_old_dentry_drop);
1652 	if (req->r_dentry_drop)
1653 		len += req->r_dentry->d_name.len;
1654 	if (req->r_old_dentry_drop)
1655 		len += req->r_old_dentry->d_name.len;
1656 
1657 	msg = ceph_msg_new(CEPH_MSG_CLIENT_REQUEST, len, GFP_NOFS, false);
1658 	if (!msg) {
1659 		msg = ERR_PTR(-ENOMEM);
1660 		goto out_free2;
1661 	}
1662 
1663 	msg->hdr.tid = cpu_to_le64(req->r_tid);
1664 
1665 	head = msg->front.iov_base;
1666 	p = msg->front.iov_base + sizeof(*head);
1667 	end = msg->front.iov_base + msg->front.iov_len;
1668 
1669 	head->mdsmap_epoch = cpu_to_le32(mdsc->mdsmap->m_epoch);
1670 	head->op = cpu_to_le32(req->r_op);
1671 	head->caller_uid = cpu_to_le32(req->r_uid);
1672 	head->caller_gid = cpu_to_le32(req->r_gid);
1673 	head->args = req->r_args;
1674 
1675 	ceph_encode_filepath(&p, end, ino1, path1);
1676 	ceph_encode_filepath(&p, end, ino2, path2);
1677 
1678 	/* make note of release offset, in case we need to replay */
1679 	req->r_request_release_offset = p - msg->front.iov_base;
1680 
1681 	/* cap releases */
1682 	releases = 0;
1683 	if (req->r_inode_drop)
1684 		releases += ceph_encode_inode_release(&p,
1685 		      req->r_inode ? req->r_inode : req->r_dentry->d_inode,
1686 		      mds, req->r_inode_drop, req->r_inode_unless, 0);
1687 	if (req->r_dentry_drop)
1688 		releases += ceph_encode_dentry_release(&p, req->r_dentry,
1689 		       mds, req->r_dentry_drop, req->r_dentry_unless);
1690 	if (req->r_old_dentry_drop)
1691 		releases += ceph_encode_dentry_release(&p, req->r_old_dentry,
1692 		       mds, req->r_old_dentry_drop, req->r_old_dentry_unless);
1693 	if (req->r_old_inode_drop)
1694 		releases += ceph_encode_inode_release(&p,
1695 		      req->r_old_dentry->d_inode,
1696 		      mds, req->r_old_inode_drop, req->r_old_inode_unless, 0);
1697 	head->num_releases = cpu_to_le16(releases);
1698 
1699 	BUG_ON(p > end);
1700 	msg->front.iov_len = p - msg->front.iov_base;
1701 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1702 
1703 	msg->pages = req->r_pages;
1704 	msg->nr_pages = req->r_num_pages;
1705 	msg->hdr.data_len = cpu_to_le32(req->r_data_len);
1706 	msg->hdr.data_off = cpu_to_le16(0);
1707 
1708 out_free2:
1709 	if (freepath2)
1710 		kfree((char *)path2);
1711 out_free1:
1712 	if (freepath1)
1713 		kfree((char *)path1);
1714 out:
1715 	return msg;
1716 }
1717 
1718 /*
1719  * called under mdsc->mutex if error, under no mutex if
1720  * success.
1721  */
1722 static void complete_request(struct ceph_mds_client *mdsc,
1723 			     struct ceph_mds_request *req)
1724 {
1725 	if (req->r_callback)
1726 		req->r_callback(mdsc, req);
1727 	else
1728 		complete_all(&req->r_completion);
1729 }
1730 
1731 /*
1732  * called under mdsc->mutex
1733  */
1734 static int __prepare_send_request(struct ceph_mds_client *mdsc,
1735 				  struct ceph_mds_request *req,
1736 				  int mds)
1737 {
1738 	struct ceph_mds_request_head *rhead;
1739 	struct ceph_msg *msg;
1740 	int flags = 0;
1741 
1742 	req->r_attempts++;
1743 	if (req->r_inode) {
1744 		struct ceph_cap *cap =
1745 			ceph_get_cap_for_mds(ceph_inode(req->r_inode), mds);
1746 
1747 		if (cap)
1748 			req->r_sent_on_mseq = cap->mseq;
1749 		else
1750 			req->r_sent_on_mseq = -1;
1751 	}
1752 	dout("prepare_send_request %p tid %lld %s (attempt %d)\n", req,
1753 	     req->r_tid, ceph_mds_op_name(req->r_op), req->r_attempts);
1754 
1755 	if (req->r_got_unsafe) {
1756 		/*
1757 		 * Replay.  Do not regenerate message (and rebuild
1758 		 * paths, etc.); just use the original message.
1759 		 * Rebuilding paths will break for renames because
1760 		 * d_move mangles the src name.
1761 		 */
1762 		msg = req->r_request;
1763 		rhead = msg->front.iov_base;
1764 
1765 		flags = le32_to_cpu(rhead->flags);
1766 		flags |= CEPH_MDS_FLAG_REPLAY;
1767 		rhead->flags = cpu_to_le32(flags);
1768 
1769 		if (req->r_target_inode)
1770 			rhead->ino = cpu_to_le64(ceph_ino(req->r_target_inode));
1771 
1772 		rhead->num_retry = req->r_attempts - 1;
1773 
1774 		/* remove cap/dentry releases from message */
1775 		rhead->num_releases = 0;
1776 		msg->hdr.front_len = cpu_to_le32(req->r_request_release_offset);
1777 		msg->front.iov_len = req->r_request_release_offset;
1778 		return 0;
1779 	}
1780 
1781 	if (req->r_request) {
1782 		ceph_msg_put(req->r_request);
1783 		req->r_request = NULL;
1784 	}
1785 	msg = create_request_message(mdsc, req, mds);
1786 	if (IS_ERR(msg)) {
1787 		req->r_err = PTR_ERR(msg);
1788 		complete_request(mdsc, req);
1789 		return PTR_ERR(msg);
1790 	}
1791 	req->r_request = msg;
1792 
1793 	rhead = msg->front.iov_base;
1794 	rhead->oldest_client_tid = cpu_to_le64(__get_oldest_tid(mdsc));
1795 	if (req->r_got_unsafe)
1796 		flags |= CEPH_MDS_FLAG_REPLAY;
1797 	if (req->r_locked_dir)
1798 		flags |= CEPH_MDS_FLAG_WANT_DENTRY;
1799 	rhead->flags = cpu_to_le32(flags);
1800 	rhead->num_fwd = req->r_num_fwd;
1801 	rhead->num_retry = req->r_attempts - 1;
1802 	rhead->ino = 0;
1803 
1804 	dout(" r_locked_dir = %p\n", req->r_locked_dir);
1805 	return 0;
1806 }
1807 
1808 /*
1809  * send request, or put it on the appropriate wait list.
1810  */
1811 static int __do_request(struct ceph_mds_client *mdsc,
1812 			struct ceph_mds_request *req)
1813 {
1814 	struct ceph_mds_session *session = NULL;
1815 	int mds = -1;
1816 	int err = -EAGAIN;
1817 
1818 	if (req->r_err || req->r_got_result)
1819 		goto out;
1820 
1821 	if (req->r_timeout &&
1822 	    time_after_eq(jiffies, req->r_started + req->r_timeout)) {
1823 		dout("do_request timed out\n");
1824 		err = -EIO;
1825 		goto finish;
1826 	}
1827 
1828 	put_request_session(req);
1829 
1830 	mds = __choose_mds(mdsc, req);
1831 	if (mds < 0 ||
1832 	    ceph_mdsmap_get_state(mdsc->mdsmap, mds) < CEPH_MDS_STATE_ACTIVE) {
1833 		dout("do_request no mds or not active, waiting for map\n");
1834 		list_add(&req->r_wait, &mdsc->waiting_for_map);
1835 		goto out;
1836 	}
1837 
1838 	/* get, open session */
1839 	session = __ceph_lookup_mds_session(mdsc, mds);
1840 	if (!session) {
1841 		session = register_session(mdsc, mds);
1842 		if (IS_ERR(session)) {
1843 			err = PTR_ERR(session);
1844 			goto finish;
1845 		}
1846 	}
1847 	req->r_session = get_session(session);
1848 
1849 	dout("do_request mds%d session %p state %s\n", mds, session,
1850 	     session_state_name(session->s_state));
1851 	if (session->s_state != CEPH_MDS_SESSION_OPEN &&
1852 	    session->s_state != CEPH_MDS_SESSION_HUNG) {
1853 		if (session->s_state == CEPH_MDS_SESSION_NEW ||
1854 		    session->s_state == CEPH_MDS_SESSION_CLOSING)
1855 			__open_session(mdsc, session);
1856 		list_add(&req->r_wait, &session->s_waiting);
1857 		goto out_session;
1858 	}
1859 
1860 	/* send request */
1861 	req->r_resend_mds = -1;   /* forget any previous mds hint */
1862 
1863 	if (req->r_request_started == 0)   /* note request start time */
1864 		req->r_request_started = jiffies;
1865 
1866 	err = __prepare_send_request(mdsc, req, mds);
1867 	if (!err) {
1868 		ceph_msg_get(req->r_request);
1869 		ceph_con_send(&session->s_con, req->r_request);
1870 	}
1871 
1872 out_session:
1873 	ceph_put_mds_session(session);
1874 out:
1875 	return err;
1876 
1877 finish:
1878 	req->r_err = err;
1879 	complete_request(mdsc, req);
1880 	goto out;
1881 }
1882 
1883 /*
1884  * called under mdsc->mutex
1885  */
1886 static void __wake_requests(struct ceph_mds_client *mdsc,
1887 			    struct list_head *head)
1888 {
1889 	struct ceph_mds_request *req, *nreq;
1890 
1891 	list_for_each_entry_safe(req, nreq, head, r_wait) {
1892 		list_del_init(&req->r_wait);
1893 		__do_request(mdsc, req);
1894 	}
1895 }
1896 
1897 /*
1898  * Wake up threads with requests pending for @mds, so that they can
1899  * resubmit their requests to a possibly different mds.
1900  */
1901 static void kick_requests(struct ceph_mds_client *mdsc, int mds)
1902 {
1903 	struct ceph_mds_request *req;
1904 	struct rb_node *p;
1905 
1906 	dout("kick_requests mds%d\n", mds);
1907 	for (p = rb_first(&mdsc->request_tree); p; p = rb_next(p)) {
1908 		req = rb_entry(p, struct ceph_mds_request, r_node);
1909 		if (req->r_got_unsafe)
1910 			continue;
1911 		if (req->r_session &&
1912 		    req->r_session->s_mds == mds) {
1913 			dout(" kicking tid %llu\n", req->r_tid);
1914 			__do_request(mdsc, req);
1915 		}
1916 	}
1917 }
1918 
1919 void ceph_mdsc_submit_request(struct ceph_mds_client *mdsc,
1920 			      struct ceph_mds_request *req)
1921 {
1922 	dout("submit_request on %p\n", req);
1923 	mutex_lock(&mdsc->mutex);
1924 	__register_request(mdsc, req, NULL);
1925 	__do_request(mdsc, req);
1926 	mutex_unlock(&mdsc->mutex);
1927 }
1928 
1929 /*
1930  * Synchrously perform an mds request.  Take care of all of the
1931  * session setup, forwarding, retry details.
1932  */
1933 int ceph_mdsc_do_request(struct ceph_mds_client *mdsc,
1934 			 struct inode *dir,
1935 			 struct ceph_mds_request *req)
1936 {
1937 	int err;
1938 
1939 	dout("do_request on %p\n", req);
1940 
1941 	/* take CAP_PIN refs for r_inode, r_locked_dir, r_old_dentry */
1942 	if (req->r_inode)
1943 		ceph_get_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
1944 	if (req->r_locked_dir)
1945 		ceph_get_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
1946 	if (req->r_old_dentry)
1947 		ceph_get_cap_refs(ceph_inode(req->r_old_dentry_dir),
1948 				  CEPH_CAP_PIN);
1949 
1950 	/* issue */
1951 	mutex_lock(&mdsc->mutex);
1952 	__register_request(mdsc, req, dir);
1953 	__do_request(mdsc, req);
1954 
1955 	if (req->r_err) {
1956 		err = req->r_err;
1957 		__unregister_request(mdsc, req);
1958 		dout("do_request early error %d\n", err);
1959 		goto out;
1960 	}
1961 
1962 	/* wait */
1963 	mutex_unlock(&mdsc->mutex);
1964 	dout("do_request waiting\n");
1965 	if (req->r_timeout) {
1966 		err = (long)wait_for_completion_killable_timeout(
1967 			&req->r_completion, req->r_timeout);
1968 		if (err == 0)
1969 			err = -EIO;
1970 	} else {
1971 		err = wait_for_completion_killable(&req->r_completion);
1972 	}
1973 	dout("do_request waited, got %d\n", err);
1974 	mutex_lock(&mdsc->mutex);
1975 
1976 	/* only abort if we didn't race with a real reply */
1977 	if (req->r_got_result) {
1978 		err = le32_to_cpu(req->r_reply_info.head->result);
1979 	} else if (err < 0) {
1980 		dout("aborted request %lld with %d\n", req->r_tid, err);
1981 
1982 		/*
1983 		 * ensure we aren't running concurrently with
1984 		 * ceph_fill_trace or ceph_readdir_prepopulate, which
1985 		 * rely on locks (dir mutex) held by our caller.
1986 		 */
1987 		mutex_lock(&req->r_fill_mutex);
1988 		req->r_err = err;
1989 		req->r_aborted = true;
1990 		mutex_unlock(&req->r_fill_mutex);
1991 
1992 		if (req->r_locked_dir &&
1993 		    (req->r_op & CEPH_MDS_OP_WRITE))
1994 			ceph_invalidate_dir_request(req);
1995 	} else {
1996 		err = req->r_err;
1997 	}
1998 
1999 out:
2000 	mutex_unlock(&mdsc->mutex);
2001 	dout("do_request %p done, result %d\n", req, err);
2002 	return err;
2003 }
2004 
2005 /*
2006  * Invalidate dir D_COMPLETE, dentry lease state on an aborted MDS
2007  * namespace request.
2008  */
2009 void ceph_invalidate_dir_request(struct ceph_mds_request *req)
2010 {
2011 	struct inode *inode = req->r_locked_dir;
2012 	struct ceph_inode_info *ci = ceph_inode(inode);
2013 
2014 	dout("invalidate_dir_request %p (D_COMPLETE, lease(s))\n", inode);
2015 	spin_lock(&ci->i_ceph_lock);
2016 	ceph_dir_clear_complete(inode);
2017 	ci->i_release_count++;
2018 	spin_unlock(&ci->i_ceph_lock);
2019 
2020 	if (req->r_dentry)
2021 		ceph_invalidate_dentry_lease(req->r_dentry);
2022 	if (req->r_old_dentry)
2023 		ceph_invalidate_dentry_lease(req->r_old_dentry);
2024 }
2025 
2026 /*
2027  * Handle mds reply.
2028  *
2029  * We take the session mutex and parse and process the reply immediately.
2030  * This preserves the logical ordering of replies, capabilities, etc., sent
2031  * by the MDS as they are applied to our local cache.
2032  */
2033 static void handle_reply(struct ceph_mds_session *session, struct ceph_msg *msg)
2034 {
2035 	struct ceph_mds_client *mdsc = session->s_mdsc;
2036 	struct ceph_mds_request *req;
2037 	struct ceph_mds_reply_head *head = msg->front.iov_base;
2038 	struct ceph_mds_reply_info_parsed *rinfo;  /* parsed reply info */
2039 	u64 tid;
2040 	int err, result;
2041 	int mds = session->s_mds;
2042 
2043 	if (msg->front.iov_len < sizeof(*head)) {
2044 		pr_err("mdsc_handle_reply got corrupt (short) reply\n");
2045 		ceph_msg_dump(msg);
2046 		return;
2047 	}
2048 
2049 	/* get request, session */
2050 	tid = le64_to_cpu(msg->hdr.tid);
2051 	mutex_lock(&mdsc->mutex);
2052 	req = __lookup_request(mdsc, tid);
2053 	if (!req) {
2054 		dout("handle_reply on unknown tid %llu\n", tid);
2055 		mutex_unlock(&mdsc->mutex);
2056 		return;
2057 	}
2058 	dout("handle_reply %p\n", req);
2059 
2060 	/* correct session? */
2061 	if (req->r_session != session) {
2062 		pr_err("mdsc_handle_reply got %llu on session mds%d"
2063 		       " not mds%d\n", tid, session->s_mds,
2064 		       req->r_session ? req->r_session->s_mds : -1);
2065 		mutex_unlock(&mdsc->mutex);
2066 		goto out;
2067 	}
2068 
2069 	/* dup? */
2070 	if ((req->r_got_unsafe && !head->safe) ||
2071 	    (req->r_got_safe && head->safe)) {
2072 		pr_warning("got a dup %s reply on %llu from mds%d\n",
2073 			   head->safe ? "safe" : "unsafe", tid, mds);
2074 		mutex_unlock(&mdsc->mutex);
2075 		goto out;
2076 	}
2077 	if (req->r_got_safe && !head->safe) {
2078 		pr_warning("got unsafe after safe on %llu from mds%d\n",
2079 			   tid, mds);
2080 		mutex_unlock(&mdsc->mutex);
2081 		goto out;
2082 	}
2083 
2084 	result = le32_to_cpu(head->result);
2085 
2086 	/*
2087 	 * Handle an ESTALE
2088 	 * if we're not talking to the authority, send to them
2089 	 * if the authority has changed while we weren't looking,
2090 	 * send to new authority
2091 	 * Otherwise we just have to return an ESTALE
2092 	 */
2093 	if (result == -ESTALE) {
2094 		dout("got ESTALE on request %llu", req->r_tid);
2095 		if (!req->r_inode) {
2096 			/* do nothing; not an authority problem */
2097 		} else if (req->r_direct_mode != USE_AUTH_MDS) {
2098 			dout("not using auth, setting for that now");
2099 			req->r_direct_mode = USE_AUTH_MDS;
2100 			__do_request(mdsc, req);
2101 			mutex_unlock(&mdsc->mutex);
2102 			goto out;
2103 		} else  {
2104 			struct ceph_inode_info *ci = ceph_inode(req->r_inode);
2105 			struct ceph_cap *cap = NULL;
2106 
2107 			if (req->r_session)
2108 				cap = ceph_get_cap_for_mds(ci,
2109 						   req->r_session->s_mds);
2110 
2111 			dout("already using auth");
2112 			if ((!cap || cap != ci->i_auth_cap) ||
2113 			    (cap->mseq != req->r_sent_on_mseq)) {
2114 				dout("but cap changed, so resending");
2115 				__do_request(mdsc, req);
2116 				mutex_unlock(&mdsc->mutex);
2117 				goto out;
2118 			}
2119 		}
2120 		dout("have to return ESTALE on request %llu", req->r_tid);
2121 	}
2122 
2123 
2124 	if (head->safe) {
2125 		req->r_got_safe = true;
2126 		__unregister_request(mdsc, req);
2127 		complete_all(&req->r_safe_completion);
2128 
2129 		if (req->r_got_unsafe) {
2130 			/*
2131 			 * We already handled the unsafe response, now do the
2132 			 * cleanup.  No need to examine the response; the MDS
2133 			 * doesn't include any result info in the safe
2134 			 * response.  And even if it did, there is nothing
2135 			 * useful we could do with a revised return value.
2136 			 */
2137 			dout("got safe reply %llu, mds%d\n", tid, mds);
2138 			list_del_init(&req->r_unsafe_item);
2139 
2140 			/* last unsafe request during umount? */
2141 			if (mdsc->stopping && !__get_oldest_req(mdsc))
2142 				complete_all(&mdsc->safe_umount_waiters);
2143 			mutex_unlock(&mdsc->mutex);
2144 			goto out;
2145 		}
2146 	} else {
2147 		req->r_got_unsafe = true;
2148 		list_add_tail(&req->r_unsafe_item, &req->r_session->s_unsafe);
2149 	}
2150 
2151 	dout("handle_reply tid %lld result %d\n", tid, result);
2152 	rinfo = &req->r_reply_info;
2153 	err = parse_reply_info(msg, rinfo, session->s_con.peer_features);
2154 	mutex_unlock(&mdsc->mutex);
2155 
2156 	mutex_lock(&session->s_mutex);
2157 	if (err < 0) {
2158 		pr_err("mdsc_handle_reply got corrupt reply mds%d(tid:%lld)\n", mds, tid);
2159 		ceph_msg_dump(msg);
2160 		goto out_err;
2161 	}
2162 
2163 	/* snap trace */
2164 	if (rinfo->snapblob_len) {
2165 		down_write(&mdsc->snap_rwsem);
2166 		ceph_update_snap_trace(mdsc, rinfo->snapblob,
2167 			       rinfo->snapblob + rinfo->snapblob_len,
2168 			       le32_to_cpu(head->op) == CEPH_MDS_OP_RMSNAP);
2169 		downgrade_write(&mdsc->snap_rwsem);
2170 	} else {
2171 		down_read(&mdsc->snap_rwsem);
2172 	}
2173 
2174 	/* insert trace into our cache */
2175 	mutex_lock(&req->r_fill_mutex);
2176 	err = ceph_fill_trace(mdsc->fsc->sb, req, req->r_session);
2177 	if (err == 0) {
2178 		if (result == 0 && req->r_op != CEPH_MDS_OP_GETFILELOCK &&
2179 		    rinfo->dir_nr)
2180 			ceph_readdir_prepopulate(req, req->r_session);
2181 		ceph_unreserve_caps(mdsc, &req->r_caps_reservation);
2182 	}
2183 	mutex_unlock(&req->r_fill_mutex);
2184 
2185 	up_read(&mdsc->snap_rwsem);
2186 out_err:
2187 	mutex_lock(&mdsc->mutex);
2188 	if (!req->r_aborted) {
2189 		if (err) {
2190 			req->r_err = err;
2191 		} else {
2192 			req->r_reply = msg;
2193 			ceph_msg_get(msg);
2194 			req->r_got_result = true;
2195 		}
2196 	} else {
2197 		dout("reply arrived after request %lld was aborted\n", tid);
2198 	}
2199 	mutex_unlock(&mdsc->mutex);
2200 
2201 	ceph_add_cap_releases(mdsc, req->r_session);
2202 	mutex_unlock(&session->s_mutex);
2203 
2204 	/* kick calling process */
2205 	complete_request(mdsc, req);
2206 out:
2207 	ceph_mdsc_put_request(req);
2208 	return;
2209 }
2210 
2211 
2212 
2213 /*
2214  * handle mds notification that our request has been forwarded.
2215  */
2216 static void handle_forward(struct ceph_mds_client *mdsc,
2217 			   struct ceph_mds_session *session,
2218 			   struct ceph_msg *msg)
2219 {
2220 	struct ceph_mds_request *req;
2221 	u64 tid = le64_to_cpu(msg->hdr.tid);
2222 	u32 next_mds;
2223 	u32 fwd_seq;
2224 	int err = -EINVAL;
2225 	void *p = msg->front.iov_base;
2226 	void *end = p + msg->front.iov_len;
2227 
2228 	ceph_decode_need(&p, end, 2*sizeof(u32), bad);
2229 	next_mds = ceph_decode_32(&p);
2230 	fwd_seq = ceph_decode_32(&p);
2231 
2232 	mutex_lock(&mdsc->mutex);
2233 	req = __lookup_request(mdsc, tid);
2234 	if (!req) {
2235 		dout("forward tid %llu to mds%d - req dne\n", tid, next_mds);
2236 		goto out;  /* dup reply? */
2237 	}
2238 
2239 	if (req->r_aborted) {
2240 		dout("forward tid %llu aborted, unregistering\n", tid);
2241 		__unregister_request(mdsc, req);
2242 	} else if (fwd_seq <= req->r_num_fwd) {
2243 		dout("forward tid %llu to mds%d - old seq %d <= %d\n",
2244 		     tid, next_mds, req->r_num_fwd, fwd_seq);
2245 	} else {
2246 		/* resend. forward race not possible; mds would drop */
2247 		dout("forward tid %llu to mds%d (we resend)\n", tid, next_mds);
2248 		BUG_ON(req->r_err);
2249 		BUG_ON(req->r_got_result);
2250 		req->r_num_fwd = fwd_seq;
2251 		req->r_resend_mds = next_mds;
2252 		put_request_session(req);
2253 		__do_request(mdsc, req);
2254 	}
2255 	ceph_mdsc_put_request(req);
2256 out:
2257 	mutex_unlock(&mdsc->mutex);
2258 	return;
2259 
2260 bad:
2261 	pr_err("mdsc_handle_forward decode error err=%d\n", err);
2262 }
2263 
2264 /*
2265  * handle a mds session control message
2266  */
2267 static void handle_session(struct ceph_mds_session *session,
2268 			   struct ceph_msg *msg)
2269 {
2270 	struct ceph_mds_client *mdsc = session->s_mdsc;
2271 	u32 op;
2272 	u64 seq;
2273 	int mds = session->s_mds;
2274 	struct ceph_mds_session_head *h = msg->front.iov_base;
2275 	int wake = 0;
2276 
2277 	/* decode */
2278 	if (msg->front.iov_len != sizeof(*h))
2279 		goto bad;
2280 	op = le32_to_cpu(h->op);
2281 	seq = le64_to_cpu(h->seq);
2282 
2283 	mutex_lock(&mdsc->mutex);
2284 	if (op == CEPH_SESSION_CLOSE)
2285 		__unregister_session(mdsc, session);
2286 	/* FIXME: this ttl calculation is generous */
2287 	session->s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose;
2288 	mutex_unlock(&mdsc->mutex);
2289 
2290 	mutex_lock(&session->s_mutex);
2291 
2292 	dout("handle_session mds%d %s %p state %s seq %llu\n",
2293 	     mds, ceph_session_op_name(op), session,
2294 	     session_state_name(session->s_state), seq);
2295 
2296 	if (session->s_state == CEPH_MDS_SESSION_HUNG) {
2297 		session->s_state = CEPH_MDS_SESSION_OPEN;
2298 		pr_info("mds%d came back\n", session->s_mds);
2299 	}
2300 
2301 	switch (op) {
2302 	case CEPH_SESSION_OPEN:
2303 		if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
2304 			pr_info("mds%d reconnect success\n", session->s_mds);
2305 		session->s_state = CEPH_MDS_SESSION_OPEN;
2306 		renewed_caps(mdsc, session, 0);
2307 		wake = 1;
2308 		if (mdsc->stopping)
2309 			__close_session(mdsc, session);
2310 		break;
2311 
2312 	case CEPH_SESSION_RENEWCAPS:
2313 		if (session->s_renew_seq == seq)
2314 			renewed_caps(mdsc, session, 1);
2315 		break;
2316 
2317 	case CEPH_SESSION_CLOSE:
2318 		if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
2319 			pr_info("mds%d reconnect denied\n", session->s_mds);
2320 		remove_session_caps(session);
2321 		wake = 1; /* for good measure */
2322 		wake_up_all(&mdsc->session_close_wq);
2323 		kick_requests(mdsc, mds);
2324 		break;
2325 
2326 	case CEPH_SESSION_STALE:
2327 		pr_info("mds%d caps went stale, renewing\n",
2328 			session->s_mds);
2329 		spin_lock(&session->s_cap_lock);
2330 		session->s_cap_gen++;
2331 		session->s_cap_ttl = 0;
2332 		spin_unlock(&session->s_cap_lock);
2333 		send_renew_caps(mdsc, session);
2334 		break;
2335 
2336 	case CEPH_SESSION_RECALL_STATE:
2337 		trim_caps(mdsc, session, le32_to_cpu(h->max_caps));
2338 		break;
2339 
2340 	default:
2341 		pr_err("mdsc_handle_session bad op %d mds%d\n", op, mds);
2342 		WARN_ON(1);
2343 	}
2344 
2345 	mutex_unlock(&session->s_mutex);
2346 	if (wake) {
2347 		mutex_lock(&mdsc->mutex);
2348 		__wake_requests(mdsc, &session->s_waiting);
2349 		mutex_unlock(&mdsc->mutex);
2350 	}
2351 	return;
2352 
2353 bad:
2354 	pr_err("mdsc_handle_session corrupt message mds%d len %d\n", mds,
2355 	       (int)msg->front.iov_len);
2356 	ceph_msg_dump(msg);
2357 	return;
2358 }
2359 
2360 
2361 /*
2362  * called under session->mutex.
2363  */
2364 static void replay_unsafe_requests(struct ceph_mds_client *mdsc,
2365 				   struct ceph_mds_session *session)
2366 {
2367 	struct ceph_mds_request *req, *nreq;
2368 	int err;
2369 
2370 	dout("replay_unsafe_requests mds%d\n", session->s_mds);
2371 
2372 	mutex_lock(&mdsc->mutex);
2373 	list_for_each_entry_safe(req, nreq, &session->s_unsafe, r_unsafe_item) {
2374 		err = __prepare_send_request(mdsc, req, session->s_mds);
2375 		if (!err) {
2376 			ceph_msg_get(req->r_request);
2377 			ceph_con_send(&session->s_con, req->r_request);
2378 		}
2379 	}
2380 	mutex_unlock(&mdsc->mutex);
2381 }
2382 
2383 /*
2384  * Encode information about a cap for a reconnect with the MDS.
2385  */
2386 static int encode_caps_cb(struct inode *inode, struct ceph_cap *cap,
2387 			  void *arg)
2388 {
2389 	union {
2390 		struct ceph_mds_cap_reconnect v2;
2391 		struct ceph_mds_cap_reconnect_v1 v1;
2392 	} rec;
2393 	size_t reclen;
2394 	struct ceph_inode_info *ci;
2395 	struct ceph_reconnect_state *recon_state = arg;
2396 	struct ceph_pagelist *pagelist = recon_state->pagelist;
2397 	char *path;
2398 	int pathlen, err;
2399 	u64 pathbase;
2400 	struct dentry *dentry;
2401 
2402 	ci = cap->ci;
2403 
2404 	dout(" adding %p ino %llx.%llx cap %p %lld %s\n",
2405 	     inode, ceph_vinop(inode), cap, cap->cap_id,
2406 	     ceph_cap_string(cap->issued));
2407 	err = ceph_pagelist_encode_64(pagelist, ceph_ino(inode));
2408 	if (err)
2409 		return err;
2410 
2411 	dentry = d_find_alias(inode);
2412 	if (dentry) {
2413 		path = ceph_mdsc_build_path(dentry, &pathlen, &pathbase, 0);
2414 		if (IS_ERR(path)) {
2415 			err = PTR_ERR(path);
2416 			goto out_dput;
2417 		}
2418 	} else {
2419 		path = NULL;
2420 		pathlen = 0;
2421 	}
2422 	err = ceph_pagelist_encode_string(pagelist, path, pathlen);
2423 	if (err)
2424 		goto out_free;
2425 
2426 	spin_lock(&ci->i_ceph_lock);
2427 	cap->seq = 0;        /* reset cap seq */
2428 	cap->issue_seq = 0;  /* and issue_seq */
2429 
2430 	if (recon_state->flock) {
2431 		rec.v2.cap_id = cpu_to_le64(cap->cap_id);
2432 		rec.v2.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2433 		rec.v2.issued = cpu_to_le32(cap->issued);
2434 		rec.v2.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2435 		rec.v2.pathbase = cpu_to_le64(pathbase);
2436 		rec.v2.flock_len = 0;
2437 		reclen = sizeof(rec.v2);
2438 	} else {
2439 		rec.v1.cap_id = cpu_to_le64(cap->cap_id);
2440 		rec.v1.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2441 		rec.v1.issued = cpu_to_le32(cap->issued);
2442 		rec.v1.size = cpu_to_le64(inode->i_size);
2443 		ceph_encode_timespec(&rec.v1.mtime, &inode->i_mtime);
2444 		ceph_encode_timespec(&rec.v1.atime, &inode->i_atime);
2445 		rec.v1.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2446 		rec.v1.pathbase = cpu_to_le64(pathbase);
2447 		reclen = sizeof(rec.v1);
2448 	}
2449 	spin_unlock(&ci->i_ceph_lock);
2450 
2451 	if (recon_state->flock) {
2452 		int num_fcntl_locks, num_flock_locks;
2453 		struct ceph_pagelist_cursor trunc_point;
2454 
2455 		ceph_pagelist_set_cursor(pagelist, &trunc_point);
2456 		do {
2457 			lock_flocks();
2458 			ceph_count_locks(inode, &num_fcntl_locks,
2459 					 &num_flock_locks);
2460 			rec.v2.flock_len = (2*sizeof(u32) +
2461 					    (num_fcntl_locks+num_flock_locks) *
2462 					    sizeof(struct ceph_filelock));
2463 			unlock_flocks();
2464 
2465 			/* pre-alloc pagelist */
2466 			ceph_pagelist_truncate(pagelist, &trunc_point);
2467 			err = ceph_pagelist_append(pagelist, &rec, reclen);
2468 			if (!err)
2469 				err = ceph_pagelist_reserve(pagelist,
2470 							    rec.v2.flock_len);
2471 
2472 			/* encode locks */
2473 			if (!err) {
2474 				lock_flocks();
2475 				err = ceph_encode_locks(inode,
2476 							pagelist,
2477 							num_fcntl_locks,
2478 							num_flock_locks);
2479 				unlock_flocks();
2480 			}
2481 		} while (err == -ENOSPC);
2482 	} else {
2483 		err = ceph_pagelist_append(pagelist, &rec, reclen);
2484 	}
2485 
2486 out_free:
2487 	kfree(path);
2488 out_dput:
2489 	dput(dentry);
2490 	return err;
2491 }
2492 
2493 
2494 /*
2495  * If an MDS fails and recovers, clients need to reconnect in order to
2496  * reestablish shared state.  This includes all caps issued through
2497  * this session _and_ the snap_realm hierarchy.  Because it's not
2498  * clear which snap realms the mds cares about, we send everything we
2499  * know about.. that ensures we'll then get any new info the
2500  * recovering MDS might have.
2501  *
2502  * This is a relatively heavyweight operation, but it's rare.
2503  *
2504  * called with mdsc->mutex held.
2505  */
2506 static void send_mds_reconnect(struct ceph_mds_client *mdsc,
2507 			       struct ceph_mds_session *session)
2508 {
2509 	struct ceph_msg *reply;
2510 	struct rb_node *p;
2511 	int mds = session->s_mds;
2512 	int err = -ENOMEM;
2513 	struct ceph_pagelist *pagelist;
2514 	struct ceph_reconnect_state recon_state;
2515 
2516 	pr_info("mds%d reconnect start\n", mds);
2517 
2518 	pagelist = kmalloc(sizeof(*pagelist), GFP_NOFS);
2519 	if (!pagelist)
2520 		goto fail_nopagelist;
2521 	ceph_pagelist_init(pagelist);
2522 
2523 	reply = ceph_msg_new(CEPH_MSG_CLIENT_RECONNECT, 0, GFP_NOFS, false);
2524 	if (!reply)
2525 		goto fail_nomsg;
2526 
2527 	mutex_lock(&session->s_mutex);
2528 	session->s_state = CEPH_MDS_SESSION_RECONNECTING;
2529 	session->s_seq = 0;
2530 
2531 	ceph_con_open(&session->s_con,
2532 		      ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
2533 
2534 	/* replay unsafe requests */
2535 	replay_unsafe_requests(mdsc, session);
2536 
2537 	down_read(&mdsc->snap_rwsem);
2538 
2539 	dout("session %p state %s\n", session,
2540 	     session_state_name(session->s_state));
2541 
2542 	/* drop old cap expires; we're about to reestablish that state */
2543 	discard_cap_releases(mdsc, session);
2544 
2545 	/* traverse this session's caps */
2546 	err = ceph_pagelist_encode_32(pagelist, session->s_nr_caps);
2547 	if (err)
2548 		goto fail;
2549 
2550 	recon_state.pagelist = pagelist;
2551 	recon_state.flock = session->s_con.peer_features & CEPH_FEATURE_FLOCK;
2552 	err = iterate_session_caps(session, encode_caps_cb, &recon_state);
2553 	if (err < 0)
2554 		goto fail;
2555 
2556 	/*
2557 	 * snaprealms.  we provide mds with the ino, seq (version), and
2558 	 * parent for all of our realms.  If the mds has any newer info,
2559 	 * it will tell us.
2560 	 */
2561 	for (p = rb_first(&mdsc->snap_realms); p; p = rb_next(p)) {
2562 		struct ceph_snap_realm *realm =
2563 			rb_entry(p, struct ceph_snap_realm, node);
2564 		struct ceph_mds_snaprealm_reconnect sr_rec;
2565 
2566 		dout(" adding snap realm %llx seq %lld parent %llx\n",
2567 		     realm->ino, realm->seq, realm->parent_ino);
2568 		sr_rec.ino = cpu_to_le64(realm->ino);
2569 		sr_rec.seq = cpu_to_le64(realm->seq);
2570 		sr_rec.parent = cpu_to_le64(realm->parent_ino);
2571 		err = ceph_pagelist_append(pagelist, &sr_rec, sizeof(sr_rec));
2572 		if (err)
2573 			goto fail;
2574 	}
2575 
2576 	reply->pagelist = pagelist;
2577 	if (recon_state.flock)
2578 		reply->hdr.version = cpu_to_le16(2);
2579 	reply->hdr.data_len = cpu_to_le32(pagelist->length);
2580 	reply->nr_pages = calc_pages_for(0, pagelist->length);
2581 	ceph_con_send(&session->s_con, reply);
2582 
2583 	mutex_unlock(&session->s_mutex);
2584 
2585 	mutex_lock(&mdsc->mutex);
2586 	__wake_requests(mdsc, &session->s_waiting);
2587 	mutex_unlock(&mdsc->mutex);
2588 
2589 	up_read(&mdsc->snap_rwsem);
2590 	return;
2591 
2592 fail:
2593 	ceph_msg_put(reply);
2594 	up_read(&mdsc->snap_rwsem);
2595 	mutex_unlock(&session->s_mutex);
2596 fail_nomsg:
2597 	ceph_pagelist_release(pagelist);
2598 	kfree(pagelist);
2599 fail_nopagelist:
2600 	pr_err("error %d preparing reconnect for mds%d\n", err, mds);
2601 	return;
2602 }
2603 
2604 
2605 /*
2606  * compare old and new mdsmaps, kicking requests
2607  * and closing out old connections as necessary
2608  *
2609  * called under mdsc->mutex.
2610  */
2611 static void check_new_map(struct ceph_mds_client *mdsc,
2612 			  struct ceph_mdsmap *newmap,
2613 			  struct ceph_mdsmap *oldmap)
2614 {
2615 	int i;
2616 	int oldstate, newstate;
2617 	struct ceph_mds_session *s;
2618 
2619 	dout("check_new_map new %u old %u\n",
2620 	     newmap->m_epoch, oldmap->m_epoch);
2621 
2622 	for (i = 0; i < oldmap->m_max_mds && i < mdsc->max_sessions; i++) {
2623 		if (mdsc->sessions[i] == NULL)
2624 			continue;
2625 		s = mdsc->sessions[i];
2626 		oldstate = ceph_mdsmap_get_state(oldmap, i);
2627 		newstate = ceph_mdsmap_get_state(newmap, i);
2628 
2629 		dout("check_new_map mds%d state %s%s -> %s%s (session %s)\n",
2630 		     i, ceph_mds_state_name(oldstate),
2631 		     ceph_mdsmap_is_laggy(oldmap, i) ? " (laggy)" : "",
2632 		     ceph_mds_state_name(newstate),
2633 		     ceph_mdsmap_is_laggy(newmap, i) ? " (laggy)" : "",
2634 		     session_state_name(s->s_state));
2635 
2636 		if (memcmp(ceph_mdsmap_get_addr(oldmap, i),
2637 			   ceph_mdsmap_get_addr(newmap, i),
2638 			   sizeof(struct ceph_entity_addr))) {
2639 			if (s->s_state == CEPH_MDS_SESSION_OPENING) {
2640 				/* the session never opened, just close it
2641 				 * out now */
2642 				__wake_requests(mdsc, &s->s_waiting);
2643 				__unregister_session(mdsc, s);
2644 			} else {
2645 				/* just close it */
2646 				mutex_unlock(&mdsc->mutex);
2647 				mutex_lock(&s->s_mutex);
2648 				mutex_lock(&mdsc->mutex);
2649 				ceph_con_close(&s->s_con);
2650 				mutex_unlock(&s->s_mutex);
2651 				s->s_state = CEPH_MDS_SESSION_RESTARTING;
2652 			}
2653 
2654 			/* kick any requests waiting on the recovering mds */
2655 			kick_requests(mdsc, i);
2656 		} else if (oldstate == newstate) {
2657 			continue;  /* nothing new with this mds */
2658 		}
2659 
2660 		/*
2661 		 * send reconnect?
2662 		 */
2663 		if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
2664 		    newstate >= CEPH_MDS_STATE_RECONNECT) {
2665 			mutex_unlock(&mdsc->mutex);
2666 			send_mds_reconnect(mdsc, s);
2667 			mutex_lock(&mdsc->mutex);
2668 		}
2669 
2670 		/*
2671 		 * kick request on any mds that has gone active.
2672 		 */
2673 		if (oldstate < CEPH_MDS_STATE_ACTIVE &&
2674 		    newstate >= CEPH_MDS_STATE_ACTIVE) {
2675 			if (oldstate != CEPH_MDS_STATE_CREATING &&
2676 			    oldstate != CEPH_MDS_STATE_STARTING)
2677 				pr_info("mds%d recovery completed\n", s->s_mds);
2678 			kick_requests(mdsc, i);
2679 			ceph_kick_flushing_caps(mdsc, s);
2680 			wake_up_session_caps(s, 1);
2681 		}
2682 	}
2683 
2684 	for (i = 0; i < newmap->m_max_mds && i < mdsc->max_sessions; i++) {
2685 		s = mdsc->sessions[i];
2686 		if (!s)
2687 			continue;
2688 		if (!ceph_mdsmap_is_laggy(newmap, i))
2689 			continue;
2690 		if (s->s_state == CEPH_MDS_SESSION_OPEN ||
2691 		    s->s_state == CEPH_MDS_SESSION_HUNG ||
2692 		    s->s_state == CEPH_MDS_SESSION_CLOSING) {
2693 			dout(" connecting to export targets of laggy mds%d\n",
2694 			     i);
2695 			__open_export_target_sessions(mdsc, s);
2696 		}
2697 	}
2698 }
2699 
2700 
2701 
2702 /*
2703  * leases
2704  */
2705 
2706 /*
2707  * caller must hold session s_mutex, dentry->d_lock
2708  */
2709 void __ceph_mdsc_drop_dentry_lease(struct dentry *dentry)
2710 {
2711 	struct ceph_dentry_info *di = ceph_dentry(dentry);
2712 
2713 	ceph_put_mds_session(di->lease_session);
2714 	di->lease_session = NULL;
2715 }
2716 
2717 static void handle_lease(struct ceph_mds_client *mdsc,
2718 			 struct ceph_mds_session *session,
2719 			 struct ceph_msg *msg)
2720 {
2721 	struct super_block *sb = mdsc->fsc->sb;
2722 	struct inode *inode;
2723 	struct dentry *parent, *dentry;
2724 	struct ceph_dentry_info *di;
2725 	int mds = session->s_mds;
2726 	struct ceph_mds_lease *h = msg->front.iov_base;
2727 	u32 seq;
2728 	struct ceph_vino vino;
2729 	struct qstr dname;
2730 	int release = 0;
2731 
2732 	dout("handle_lease from mds%d\n", mds);
2733 
2734 	/* decode */
2735 	if (msg->front.iov_len < sizeof(*h) + sizeof(u32))
2736 		goto bad;
2737 	vino.ino = le64_to_cpu(h->ino);
2738 	vino.snap = CEPH_NOSNAP;
2739 	seq = le32_to_cpu(h->seq);
2740 	dname.name = (void *)h + sizeof(*h) + sizeof(u32);
2741 	dname.len = msg->front.iov_len - sizeof(*h) - sizeof(u32);
2742 	if (dname.len != get_unaligned_le32(h+1))
2743 		goto bad;
2744 
2745 	mutex_lock(&session->s_mutex);
2746 	session->s_seq++;
2747 
2748 	/* lookup inode */
2749 	inode = ceph_find_inode(sb, vino);
2750 	dout("handle_lease %s, ino %llx %p %.*s\n",
2751 	     ceph_lease_op_name(h->action), vino.ino, inode,
2752 	     dname.len, dname.name);
2753 	if (inode == NULL) {
2754 		dout("handle_lease no inode %llx\n", vino.ino);
2755 		goto release;
2756 	}
2757 
2758 	/* dentry */
2759 	parent = d_find_alias(inode);
2760 	if (!parent) {
2761 		dout("no parent dentry on inode %p\n", inode);
2762 		WARN_ON(1);
2763 		goto release;  /* hrm... */
2764 	}
2765 	dname.hash = full_name_hash(dname.name, dname.len);
2766 	dentry = d_lookup(parent, &dname);
2767 	dput(parent);
2768 	if (!dentry)
2769 		goto release;
2770 
2771 	spin_lock(&dentry->d_lock);
2772 	di = ceph_dentry(dentry);
2773 	switch (h->action) {
2774 	case CEPH_MDS_LEASE_REVOKE:
2775 		if (di->lease_session == session) {
2776 			if (ceph_seq_cmp(di->lease_seq, seq) > 0)
2777 				h->seq = cpu_to_le32(di->lease_seq);
2778 			__ceph_mdsc_drop_dentry_lease(dentry);
2779 		}
2780 		release = 1;
2781 		break;
2782 
2783 	case CEPH_MDS_LEASE_RENEW:
2784 		if (di->lease_session == session &&
2785 		    di->lease_gen == session->s_cap_gen &&
2786 		    di->lease_renew_from &&
2787 		    di->lease_renew_after == 0) {
2788 			unsigned long duration =
2789 				le32_to_cpu(h->duration_ms) * HZ / 1000;
2790 
2791 			di->lease_seq = seq;
2792 			dentry->d_time = di->lease_renew_from + duration;
2793 			di->lease_renew_after = di->lease_renew_from +
2794 				(duration >> 1);
2795 			di->lease_renew_from = 0;
2796 		}
2797 		break;
2798 	}
2799 	spin_unlock(&dentry->d_lock);
2800 	dput(dentry);
2801 
2802 	if (!release)
2803 		goto out;
2804 
2805 release:
2806 	/* let's just reuse the same message */
2807 	h->action = CEPH_MDS_LEASE_REVOKE_ACK;
2808 	ceph_msg_get(msg);
2809 	ceph_con_send(&session->s_con, msg);
2810 
2811 out:
2812 	iput(inode);
2813 	mutex_unlock(&session->s_mutex);
2814 	return;
2815 
2816 bad:
2817 	pr_err("corrupt lease message\n");
2818 	ceph_msg_dump(msg);
2819 }
2820 
2821 void ceph_mdsc_lease_send_msg(struct ceph_mds_session *session,
2822 			      struct inode *inode,
2823 			      struct dentry *dentry, char action,
2824 			      u32 seq)
2825 {
2826 	struct ceph_msg *msg;
2827 	struct ceph_mds_lease *lease;
2828 	int len = sizeof(*lease) + sizeof(u32);
2829 	int dnamelen = 0;
2830 
2831 	dout("lease_send_msg inode %p dentry %p %s to mds%d\n",
2832 	     inode, dentry, ceph_lease_op_name(action), session->s_mds);
2833 	dnamelen = dentry->d_name.len;
2834 	len += dnamelen;
2835 
2836 	msg = ceph_msg_new(CEPH_MSG_CLIENT_LEASE, len, GFP_NOFS, false);
2837 	if (!msg)
2838 		return;
2839 	lease = msg->front.iov_base;
2840 	lease->action = action;
2841 	lease->ino = cpu_to_le64(ceph_vino(inode).ino);
2842 	lease->first = lease->last = cpu_to_le64(ceph_vino(inode).snap);
2843 	lease->seq = cpu_to_le32(seq);
2844 	put_unaligned_le32(dnamelen, lease + 1);
2845 	memcpy((void *)(lease + 1) + 4, dentry->d_name.name, dnamelen);
2846 
2847 	/*
2848 	 * if this is a preemptive lease RELEASE, no need to
2849 	 * flush request stream, since the actual request will
2850 	 * soon follow.
2851 	 */
2852 	msg->more_to_follow = (action == CEPH_MDS_LEASE_RELEASE);
2853 
2854 	ceph_con_send(&session->s_con, msg);
2855 }
2856 
2857 /*
2858  * Preemptively release a lease we expect to invalidate anyway.
2859  * Pass @inode always, @dentry is optional.
2860  */
2861 void ceph_mdsc_lease_release(struct ceph_mds_client *mdsc, struct inode *inode,
2862 			     struct dentry *dentry)
2863 {
2864 	struct ceph_dentry_info *di;
2865 	struct ceph_mds_session *session;
2866 	u32 seq;
2867 
2868 	BUG_ON(inode == NULL);
2869 	BUG_ON(dentry == NULL);
2870 
2871 	/* is dentry lease valid? */
2872 	spin_lock(&dentry->d_lock);
2873 	di = ceph_dentry(dentry);
2874 	if (!di || !di->lease_session ||
2875 	    di->lease_session->s_mds < 0 ||
2876 	    di->lease_gen != di->lease_session->s_cap_gen ||
2877 	    !time_before(jiffies, dentry->d_time)) {
2878 		dout("lease_release inode %p dentry %p -- "
2879 		     "no lease\n",
2880 		     inode, dentry);
2881 		spin_unlock(&dentry->d_lock);
2882 		return;
2883 	}
2884 
2885 	/* we do have a lease on this dentry; note mds and seq */
2886 	session = ceph_get_mds_session(di->lease_session);
2887 	seq = di->lease_seq;
2888 	__ceph_mdsc_drop_dentry_lease(dentry);
2889 	spin_unlock(&dentry->d_lock);
2890 
2891 	dout("lease_release inode %p dentry %p to mds%d\n",
2892 	     inode, dentry, session->s_mds);
2893 	ceph_mdsc_lease_send_msg(session, inode, dentry,
2894 				 CEPH_MDS_LEASE_RELEASE, seq);
2895 	ceph_put_mds_session(session);
2896 }
2897 
2898 /*
2899  * drop all leases (and dentry refs) in preparation for umount
2900  */
2901 static void drop_leases(struct ceph_mds_client *mdsc)
2902 {
2903 	int i;
2904 
2905 	dout("drop_leases\n");
2906 	mutex_lock(&mdsc->mutex);
2907 	for (i = 0; i < mdsc->max_sessions; i++) {
2908 		struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2909 		if (!s)
2910 			continue;
2911 		mutex_unlock(&mdsc->mutex);
2912 		mutex_lock(&s->s_mutex);
2913 		mutex_unlock(&s->s_mutex);
2914 		ceph_put_mds_session(s);
2915 		mutex_lock(&mdsc->mutex);
2916 	}
2917 	mutex_unlock(&mdsc->mutex);
2918 }
2919 
2920 
2921 
2922 /*
2923  * delayed work -- periodically trim expired leases, renew caps with mds
2924  */
2925 static void schedule_delayed(struct ceph_mds_client *mdsc)
2926 {
2927 	int delay = 5;
2928 	unsigned hz = round_jiffies_relative(HZ * delay);
2929 	schedule_delayed_work(&mdsc->delayed_work, hz);
2930 }
2931 
2932 static void delayed_work(struct work_struct *work)
2933 {
2934 	int i;
2935 	struct ceph_mds_client *mdsc =
2936 		container_of(work, struct ceph_mds_client, delayed_work.work);
2937 	int renew_interval;
2938 	int renew_caps;
2939 
2940 	dout("mdsc delayed_work\n");
2941 	ceph_check_delayed_caps(mdsc);
2942 
2943 	mutex_lock(&mdsc->mutex);
2944 	renew_interval = mdsc->mdsmap->m_session_timeout >> 2;
2945 	renew_caps = time_after_eq(jiffies, HZ*renew_interval +
2946 				   mdsc->last_renew_caps);
2947 	if (renew_caps)
2948 		mdsc->last_renew_caps = jiffies;
2949 
2950 	for (i = 0; i < mdsc->max_sessions; i++) {
2951 		struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2952 		if (s == NULL)
2953 			continue;
2954 		if (s->s_state == CEPH_MDS_SESSION_CLOSING) {
2955 			dout("resending session close request for mds%d\n",
2956 			     s->s_mds);
2957 			request_close_session(mdsc, s);
2958 			ceph_put_mds_session(s);
2959 			continue;
2960 		}
2961 		if (s->s_ttl && time_after(jiffies, s->s_ttl)) {
2962 			if (s->s_state == CEPH_MDS_SESSION_OPEN) {
2963 				s->s_state = CEPH_MDS_SESSION_HUNG;
2964 				pr_info("mds%d hung\n", s->s_mds);
2965 			}
2966 		}
2967 		if (s->s_state < CEPH_MDS_SESSION_OPEN) {
2968 			/* this mds is failed or recovering, just wait */
2969 			ceph_put_mds_session(s);
2970 			continue;
2971 		}
2972 		mutex_unlock(&mdsc->mutex);
2973 
2974 		mutex_lock(&s->s_mutex);
2975 		if (renew_caps)
2976 			send_renew_caps(mdsc, s);
2977 		else
2978 			ceph_con_keepalive(&s->s_con);
2979 		ceph_add_cap_releases(mdsc, s);
2980 		if (s->s_state == CEPH_MDS_SESSION_OPEN ||
2981 		    s->s_state == CEPH_MDS_SESSION_HUNG)
2982 			ceph_send_cap_releases(mdsc, s);
2983 		mutex_unlock(&s->s_mutex);
2984 		ceph_put_mds_session(s);
2985 
2986 		mutex_lock(&mdsc->mutex);
2987 	}
2988 	mutex_unlock(&mdsc->mutex);
2989 
2990 	schedule_delayed(mdsc);
2991 }
2992 
2993 int ceph_mdsc_init(struct ceph_fs_client *fsc)
2994 
2995 {
2996 	struct ceph_mds_client *mdsc;
2997 
2998 	mdsc = kzalloc(sizeof(struct ceph_mds_client), GFP_NOFS);
2999 	if (!mdsc)
3000 		return -ENOMEM;
3001 	mdsc->fsc = fsc;
3002 	fsc->mdsc = mdsc;
3003 	mutex_init(&mdsc->mutex);
3004 	mdsc->mdsmap = kzalloc(sizeof(*mdsc->mdsmap), GFP_NOFS);
3005 	if (mdsc->mdsmap == NULL)
3006 		return -ENOMEM;
3007 
3008 	init_completion(&mdsc->safe_umount_waiters);
3009 	init_waitqueue_head(&mdsc->session_close_wq);
3010 	INIT_LIST_HEAD(&mdsc->waiting_for_map);
3011 	mdsc->sessions = NULL;
3012 	mdsc->max_sessions = 0;
3013 	mdsc->stopping = 0;
3014 	init_rwsem(&mdsc->snap_rwsem);
3015 	mdsc->snap_realms = RB_ROOT;
3016 	INIT_LIST_HEAD(&mdsc->snap_empty);
3017 	spin_lock_init(&mdsc->snap_empty_lock);
3018 	mdsc->last_tid = 0;
3019 	mdsc->request_tree = RB_ROOT;
3020 	INIT_DELAYED_WORK(&mdsc->delayed_work, delayed_work);
3021 	mdsc->last_renew_caps = jiffies;
3022 	INIT_LIST_HEAD(&mdsc->cap_delay_list);
3023 	spin_lock_init(&mdsc->cap_delay_lock);
3024 	INIT_LIST_HEAD(&mdsc->snap_flush_list);
3025 	spin_lock_init(&mdsc->snap_flush_lock);
3026 	mdsc->cap_flush_seq = 0;
3027 	INIT_LIST_HEAD(&mdsc->cap_dirty);
3028 	INIT_LIST_HEAD(&mdsc->cap_dirty_migrating);
3029 	mdsc->num_cap_flushing = 0;
3030 	spin_lock_init(&mdsc->cap_dirty_lock);
3031 	init_waitqueue_head(&mdsc->cap_flushing_wq);
3032 	spin_lock_init(&mdsc->dentry_lru_lock);
3033 	INIT_LIST_HEAD(&mdsc->dentry_lru);
3034 
3035 	ceph_caps_init(mdsc);
3036 	ceph_adjust_min_caps(mdsc, fsc->min_caps);
3037 
3038 	return 0;
3039 }
3040 
3041 /*
3042  * Wait for safe replies on open mds requests.  If we time out, drop
3043  * all requests from the tree to avoid dangling dentry refs.
3044  */
3045 static void wait_requests(struct ceph_mds_client *mdsc)
3046 {
3047 	struct ceph_mds_request *req;
3048 	struct ceph_fs_client *fsc = mdsc->fsc;
3049 
3050 	mutex_lock(&mdsc->mutex);
3051 	if (__get_oldest_req(mdsc)) {
3052 		mutex_unlock(&mdsc->mutex);
3053 
3054 		dout("wait_requests waiting for requests\n");
3055 		wait_for_completion_timeout(&mdsc->safe_umount_waiters,
3056 				    fsc->client->options->mount_timeout * HZ);
3057 
3058 		/* tear down remaining requests */
3059 		mutex_lock(&mdsc->mutex);
3060 		while ((req = __get_oldest_req(mdsc))) {
3061 			dout("wait_requests timed out on tid %llu\n",
3062 			     req->r_tid);
3063 			__unregister_request(mdsc, req);
3064 		}
3065 	}
3066 	mutex_unlock(&mdsc->mutex);
3067 	dout("wait_requests done\n");
3068 }
3069 
3070 /*
3071  * called before mount is ro, and before dentries are torn down.
3072  * (hmm, does this still race with new lookups?)
3073  */
3074 void ceph_mdsc_pre_umount(struct ceph_mds_client *mdsc)
3075 {
3076 	dout("pre_umount\n");
3077 	mdsc->stopping = 1;
3078 
3079 	drop_leases(mdsc);
3080 	ceph_flush_dirty_caps(mdsc);
3081 	wait_requests(mdsc);
3082 
3083 	/*
3084 	 * wait for reply handlers to drop their request refs and
3085 	 * their inode/dcache refs
3086 	 */
3087 	ceph_msgr_flush();
3088 }
3089 
3090 /*
3091  * wait for all write mds requests to flush.
3092  */
3093 static void wait_unsafe_requests(struct ceph_mds_client *mdsc, u64 want_tid)
3094 {
3095 	struct ceph_mds_request *req = NULL, *nextreq;
3096 	struct rb_node *n;
3097 
3098 	mutex_lock(&mdsc->mutex);
3099 	dout("wait_unsafe_requests want %lld\n", want_tid);
3100 restart:
3101 	req = __get_oldest_req(mdsc);
3102 	while (req && req->r_tid <= want_tid) {
3103 		/* find next request */
3104 		n = rb_next(&req->r_node);
3105 		if (n)
3106 			nextreq = rb_entry(n, struct ceph_mds_request, r_node);
3107 		else
3108 			nextreq = NULL;
3109 		if ((req->r_op & CEPH_MDS_OP_WRITE)) {
3110 			/* write op */
3111 			ceph_mdsc_get_request(req);
3112 			if (nextreq)
3113 				ceph_mdsc_get_request(nextreq);
3114 			mutex_unlock(&mdsc->mutex);
3115 			dout("wait_unsafe_requests  wait on %llu (want %llu)\n",
3116 			     req->r_tid, want_tid);
3117 			wait_for_completion(&req->r_safe_completion);
3118 			mutex_lock(&mdsc->mutex);
3119 			ceph_mdsc_put_request(req);
3120 			if (!nextreq)
3121 				break;  /* next dne before, so we're done! */
3122 			if (RB_EMPTY_NODE(&nextreq->r_node)) {
3123 				/* next request was removed from tree */
3124 				ceph_mdsc_put_request(nextreq);
3125 				goto restart;
3126 			}
3127 			ceph_mdsc_put_request(nextreq);  /* won't go away */
3128 		}
3129 		req = nextreq;
3130 	}
3131 	mutex_unlock(&mdsc->mutex);
3132 	dout("wait_unsafe_requests done\n");
3133 }
3134 
3135 void ceph_mdsc_sync(struct ceph_mds_client *mdsc)
3136 {
3137 	u64 want_tid, want_flush;
3138 
3139 	if (mdsc->fsc->mount_state == CEPH_MOUNT_SHUTDOWN)
3140 		return;
3141 
3142 	dout("sync\n");
3143 	mutex_lock(&mdsc->mutex);
3144 	want_tid = mdsc->last_tid;
3145 	want_flush = mdsc->cap_flush_seq;
3146 	mutex_unlock(&mdsc->mutex);
3147 	dout("sync want tid %lld flush_seq %lld\n", want_tid, want_flush);
3148 
3149 	ceph_flush_dirty_caps(mdsc);
3150 
3151 	wait_unsafe_requests(mdsc, want_tid);
3152 	wait_event(mdsc->cap_flushing_wq, check_cap_flush(mdsc, want_flush));
3153 }
3154 
3155 /*
3156  * true if all sessions are closed, or we force unmount
3157  */
3158 static bool done_closing_sessions(struct ceph_mds_client *mdsc)
3159 {
3160 	int i, n = 0;
3161 
3162 	if (mdsc->fsc->mount_state == CEPH_MOUNT_SHUTDOWN)
3163 		return true;
3164 
3165 	mutex_lock(&mdsc->mutex);
3166 	for (i = 0; i < mdsc->max_sessions; i++)
3167 		if (mdsc->sessions[i])
3168 			n++;
3169 	mutex_unlock(&mdsc->mutex);
3170 	return n == 0;
3171 }
3172 
3173 /*
3174  * called after sb is ro.
3175  */
3176 void ceph_mdsc_close_sessions(struct ceph_mds_client *mdsc)
3177 {
3178 	struct ceph_mds_session *session;
3179 	int i;
3180 	struct ceph_fs_client *fsc = mdsc->fsc;
3181 	unsigned long timeout = fsc->client->options->mount_timeout * HZ;
3182 
3183 	dout("close_sessions\n");
3184 
3185 	/* close sessions */
3186 	mutex_lock(&mdsc->mutex);
3187 	for (i = 0; i < mdsc->max_sessions; i++) {
3188 		session = __ceph_lookup_mds_session(mdsc, i);
3189 		if (!session)
3190 			continue;
3191 		mutex_unlock(&mdsc->mutex);
3192 		mutex_lock(&session->s_mutex);
3193 		__close_session(mdsc, session);
3194 		mutex_unlock(&session->s_mutex);
3195 		ceph_put_mds_session(session);
3196 		mutex_lock(&mdsc->mutex);
3197 	}
3198 	mutex_unlock(&mdsc->mutex);
3199 
3200 	dout("waiting for sessions to close\n");
3201 	wait_event_timeout(mdsc->session_close_wq, done_closing_sessions(mdsc),
3202 			   timeout);
3203 
3204 	/* tear down remaining sessions */
3205 	mutex_lock(&mdsc->mutex);
3206 	for (i = 0; i < mdsc->max_sessions; i++) {
3207 		if (mdsc->sessions[i]) {
3208 			session = get_session(mdsc->sessions[i]);
3209 			__unregister_session(mdsc, session);
3210 			mutex_unlock(&mdsc->mutex);
3211 			mutex_lock(&session->s_mutex);
3212 			remove_session_caps(session);
3213 			mutex_unlock(&session->s_mutex);
3214 			ceph_put_mds_session(session);
3215 			mutex_lock(&mdsc->mutex);
3216 		}
3217 	}
3218 	WARN_ON(!list_empty(&mdsc->cap_delay_list));
3219 	mutex_unlock(&mdsc->mutex);
3220 
3221 	ceph_cleanup_empty_realms(mdsc);
3222 
3223 	cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
3224 
3225 	dout("stopped\n");
3226 }
3227 
3228 static void ceph_mdsc_stop(struct ceph_mds_client *mdsc)
3229 {
3230 	dout("stop\n");
3231 	cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
3232 	if (mdsc->mdsmap)
3233 		ceph_mdsmap_destroy(mdsc->mdsmap);
3234 	kfree(mdsc->sessions);
3235 	ceph_caps_finalize(mdsc);
3236 }
3237 
3238 void ceph_mdsc_destroy(struct ceph_fs_client *fsc)
3239 {
3240 	struct ceph_mds_client *mdsc = fsc->mdsc;
3241 
3242 	dout("mdsc_destroy %p\n", mdsc);
3243 	ceph_mdsc_stop(mdsc);
3244 
3245 	/* flush out any connection work with references to us */
3246 	ceph_msgr_flush();
3247 
3248 	fsc->mdsc = NULL;
3249 	kfree(mdsc);
3250 	dout("mdsc_destroy %p done\n", mdsc);
3251 }
3252 
3253 
3254 /*
3255  * handle mds map update.
3256  */
3257 void ceph_mdsc_handle_map(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
3258 {
3259 	u32 epoch;
3260 	u32 maplen;
3261 	void *p = msg->front.iov_base;
3262 	void *end = p + msg->front.iov_len;
3263 	struct ceph_mdsmap *newmap, *oldmap;
3264 	struct ceph_fsid fsid;
3265 	int err = -EINVAL;
3266 
3267 	ceph_decode_need(&p, end, sizeof(fsid)+2*sizeof(u32), bad);
3268 	ceph_decode_copy(&p, &fsid, sizeof(fsid));
3269 	if (ceph_check_fsid(mdsc->fsc->client, &fsid) < 0)
3270 		return;
3271 	epoch = ceph_decode_32(&p);
3272 	maplen = ceph_decode_32(&p);
3273 	dout("handle_map epoch %u len %d\n", epoch, (int)maplen);
3274 
3275 	/* do we need it? */
3276 	ceph_monc_got_mdsmap(&mdsc->fsc->client->monc, epoch);
3277 	mutex_lock(&mdsc->mutex);
3278 	if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) {
3279 		dout("handle_map epoch %u <= our %u\n",
3280 		     epoch, mdsc->mdsmap->m_epoch);
3281 		mutex_unlock(&mdsc->mutex);
3282 		return;
3283 	}
3284 
3285 	newmap = ceph_mdsmap_decode(&p, end);
3286 	if (IS_ERR(newmap)) {
3287 		err = PTR_ERR(newmap);
3288 		goto bad_unlock;
3289 	}
3290 
3291 	/* swap into place */
3292 	if (mdsc->mdsmap) {
3293 		oldmap = mdsc->mdsmap;
3294 		mdsc->mdsmap = newmap;
3295 		check_new_map(mdsc, newmap, oldmap);
3296 		ceph_mdsmap_destroy(oldmap);
3297 	} else {
3298 		mdsc->mdsmap = newmap;  /* first mds map */
3299 	}
3300 	mdsc->fsc->sb->s_maxbytes = mdsc->mdsmap->m_max_file_size;
3301 
3302 	__wake_requests(mdsc, &mdsc->waiting_for_map);
3303 
3304 	mutex_unlock(&mdsc->mutex);
3305 	schedule_delayed(mdsc);
3306 	return;
3307 
3308 bad_unlock:
3309 	mutex_unlock(&mdsc->mutex);
3310 bad:
3311 	pr_err("error decoding mdsmap %d\n", err);
3312 	return;
3313 }
3314 
3315 static struct ceph_connection *con_get(struct ceph_connection *con)
3316 {
3317 	struct ceph_mds_session *s = con->private;
3318 
3319 	if (get_session(s)) {
3320 		dout("mdsc con_get %p ok (%d)\n", s, atomic_read(&s->s_ref));
3321 		return con;
3322 	}
3323 	dout("mdsc con_get %p FAIL\n", s);
3324 	return NULL;
3325 }
3326 
3327 static void con_put(struct ceph_connection *con)
3328 {
3329 	struct ceph_mds_session *s = con->private;
3330 
3331 	dout("mdsc con_put %p (%d)\n", s, atomic_read(&s->s_ref) - 1);
3332 	ceph_put_mds_session(s);
3333 }
3334 
3335 /*
3336  * if the client is unresponsive for long enough, the mds will kill
3337  * the session entirely.
3338  */
3339 static void peer_reset(struct ceph_connection *con)
3340 {
3341 	struct ceph_mds_session *s = con->private;
3342 	struct ceph_mds_client *mdsc = s->s_mdsc;
3343 
3344 	pr_warning("mds%d closed our session\n", s->s_mds);
3345 	send_mds_reconnect(mdsc, s);
3346 }
3347 
3348 static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
3349 {
3350 	struct ceph_mds_session *s = con->private;
3351 	struct ceph_mds_client *mdsc = s->s_mdsc;
3352 	int type = le16_to_cpu(msg->hdr.type);
3353 
3354 	mutex_lock(&mdsc->mutex);
3355 	if (__verify_registered_session(mdsc, s) < 0) {
3356 		mutex_unlock(&mdsc->mutex);
3357 		goto out;
3358 	}
3359 	mutex_unlock(&mdsc->mutex);
3360 
3361 	switch (type) {
3362 	case CEPH_MSG_MDS_MAP:
3363 		ceph_mdsc_handle_map(mdsc, msg);
3364 		break;
3365 	case CEPH_MSG_CLIENT_SESSION:
3366 		handle_session(s, msg);
3367 		break;
3368 	case CEPH_MSG_CLIENT_REPLY:
3369 		handle_reply(s, msg);
3370 		break;
3371 	case CEPH_MSG_CLIENT_REQUEST_FORWARD:
3372 		handle_forward(mdsc, s, msg);
3373 		break;
3374 	case CEPH_MSG_CLIENT_CAPS:
3375 		ceph_handle_caps(s, msg);
3376 		break;
3377 	case CEPH_MSG_CLIENT_SNAP:
3378 		ceph_handle_snap(mdsc, s, msg);
3379 		break;
3380 	case CEPH_MSG_CLIENT_LEASE:
3381 		handle_lease(mdsc, s, msg);
3382 		break;
3383 
3384 	default:
3385 		pr_err("received unknown message type %d %s\n", type,
3386 		       ceph_msg_type_name(type));
3387 	}
3388 out:
3389 	ceph_msg_put(msg);
3390 }
3391 
3392 /*
3393  * authentication
3394  */
3395 static int get_authorizer(struct ceph_connection *con,
3396 			  void **buf, int *len, int *proto,
3397 			  void **reply_buf, int *reply_len, int force_new)
3398 {
3399 	struct ceph_mds_session *s = con->private;
3400 	struct ceph_mds_client *mdsc = s->s_mdsc;
3401 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3402 	int ret = 0;
3403 
3404 	if (force_new && s->s_authorizer) {
3405 		ac->ops->destroy_authorizer(ac, s->s_authorizer);
3406 		s->s_authorizer = NULL;
3407 	}
3408 	if (s->s_authorizer == NULL) {
3409 		if (ac->ops->create_authorizer) {
3410 			ret = ac->ops->create_authorizer(
3411 				ac, CEPH_ENTITY_TYPE_MDS,
3412 				&s->s_authorizer,
3413 				&s->s_authorizer_buf,
3414 				&s->s_authorizer_buf_len,
3415 				&s->s_authorizer_reply_buf,
3416 				&s->s_authorizer_reply_buf_len);
3417 			if (ret)
3418 				return ret;
3419 		}
3420 	}
3421 
3422 	*proto = ac->protocol;
3423 	*buf = s->s_authorizer_buf;
3424 	*len = s->s_authorizer_buf_len;
3425 	*reply_buf = s->s_authorizer_reply_buf;
3426 	*reply_len = s->s_authorizer_reply_buf_len;
3427 	return 0;
3428 }
3429 
3430 
3431 static int verify_authorizer_reply(struct ceph_connection *con, int len)
3432 {
3433 	struct ceph_mds_session *s = con->private;
3434 	struct ceph_mds_client *mdsc = s->s_mdsc;
3435 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3436 
3437 	return ac->ops->verify_authorizer_reply(ac, s->s_authorizer, len);
3438 }
3439 
3440 static int invalidate_authorizer(struct ceph_connection *con)
3441 {
3442 	struct ceph_mds_session *s = con->private;
3443 	struct ceph_mds_client *mdsc = s->s_mdsc;
3444 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3445 
3446 	if (ac->ops->invalidate_authorizer)
3447 		ac->ops->invalidate_authorizer(ac, CEPH_ENTITY_TYPE_MDS);
3448 
3449 	return ceph_monc_validate_auth(&mdsc->fsc->client->monc);
3450 }
3451 
3452 static const struct ceph_connection_operations mds_con_ops = {
3453 	.get = con_get,
3454 	.put = con_put,
3455 	.dispatch = dispatch,
3456 	.get_authorizer = get_authorizer,
3457 	.verify_authorizer_reply = verify_authorizer_reply,
3458 	.invalidate_authorizer = invalidate_authorizer,
3459 	.peer_reset = peer_reset,
3460 };
3461 
3462 /* eof */
3463