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