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