ceph: use rbtree for mds requests
[linux-2.6.git] / fs / ceph / mds_client.c
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_iterating_caps = false;
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 ceph_cap *cap, *ncap;
733         struct inode *inode;
734         int ret;
735
736         dout("iterate_session_caps %p mds%d\n", session, session->s_mds);
737         spin_lock(&session->s_cap_lock);
738         session->s_iterating_caps = true;
739         list_for_each_entry_safe(cap, ncap, &session->s_caps, session_caps) {
740                 inode = igrab(&cap->ci->vfs_inode);
741                 if (!inode)
742                         continue;
743                 spin_unlock(&session->s_cap_lock);
744                 ret = cb(inode, cap, arg);
745                 iput(inode);
746                 spin_lock(&session->s_cap_lock);
747                 if (ret < 0)
748                         goto out;
749         }
750         ret = 0;
751 out:
752         session->s_iterating_caps = false;
753         spin_unlock(&session->s_cap_lock);
754         return ret;
755 }
756
757 static int remove_session_caps_cb(struct inode *inode, struct ceph_cap *cap,
758                                    void *arg)
759 {
760         struct ceph_inode_info *ci = ceph_inode(inode);
761         dout("removing cap %p, ci is %p, inode is %p\n",
762              cap, ci, &ci->vfs_inode);
763         ceph_remove_cap(cap);
764         return 0;
765 }
766
767 /*
768  * caller must hold session s_mutex
769  */
770 static void remove_session_caps(struct ceph_mds_session *session)
771 {
772         dout("remove_session_caps on %p\n", session);
773         iterate_session_caps(session, remove_session_caps_cb, NULL);
774         BUG_ON(session->s_nr_caps > 0);
775         cleanup_cap_releases(session);
776 }
777
778 /*
779  * wake up any threads waiting on this session's caps.  if the cap is
780  * old (didn't get renewed on the client reconnect), remove it now.
781  *
782  * caller must hold s_mutex.
783  */
784 static int wake_up_session_cb(struct inode *inode, struct ceph_cap *cap,
785                               void *arg)
786 {
787         struct ceph_inode_info *ci = ceph_inode(inode);
788
789         wake_up(&ci->i_cap_wq);
790         if (arg) {
791                 spin_lock(&inode->i_lock);
792                 ci->i_wanted_max_size = 0;
793                 ci->i_requested_max_size = 0;
794                 spin_unlock(&inode->i_lock);
795         }
796         return 0;
797 }
798
799 static void wake_up_session_caps(struct ceph_mds_session *session,
800                                  int reconnect)
801 {
802         dout("wake_up_session_caps %p mds%d\n", session, session->s_mds);
803         iterate_session_caps(session, wake_up_session_cb,
804                              (void *)(unsigned long)reconnect);
805 }
806
807 /*
808  * Send periodic message to MDS renewing all currently held caps.  The
809  * ack will reset the expiration for all caps from this session.
810  *
811  * caller holds s_mutex
812  */
813 static int send_renew_caps(struct ceph_mds_client *mdsc,
814                            struct ceph_mds_session *session)
815 {
816         struct ceph_msg *msg;
817         int state;
818
819         if (time_after_eq(jiffies, session->s_cap_ttl) &&
820             time_after_eq(session->s_cap_ttl, session->s_renew_requested))
821                 pr_info("mds%d caps stale\n", session->s_mds);
822
823         /* do not try to renew caps until a recovering mds has reconnected
824          * with its clients. */
825         state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
826         if (state < CEPH_MDS_STATE_RECONNECT) {
827                 dout("send_renew_caps ignoring mds%d (%s)\n",
828                      session->s_mds, ceph_mds_state_name(state));
829                 return 0;
830         }
831
832         dout("send_renew_caps to mds%d (%s)\n", session->s_mds,
833                 ceph_mds_state_name(state));
834         session->s_renew_requested = jiffies;
835         msg = create_session_msg(CEPH_SESSION_REQUEST_RENEWCAPS,
836                                  ++session->s_renew_seq);
837         if (IS_ERR(msg))
838                 return PTR_ERR(msg);
839         ceph_con_send(&session->s_con, msg);
840         return 0;
841 }
842
843 /*
844  * Note new cap ttl, and any transition from stale -> not stale (fresh?).
845  *
846  * Called under session->s_mutex
847  */
848 static void renewed_caps(struct ceph_mds_client *mdsc,
849                          struct ceph_mds_session *session, int is_renew)
850 {
851         int was_stale;
852         int wake = 0;
853
854         spin_lock(&session->s_cap_lock);
855         was_stale = is_renew && (session->s_cap_ttl == 0 ||
856                                  time_after_eq(jiffies, session->s_cap_ttl));
857
858         session->s_cap_ttl = session->s_renew_requested +
859                 mdsc->mdsmap->m_session_timeout*HZ;
860
861         if (was_stale) {
862                 if (time_before(jiffies, session->s_cap_ttl)) {
863                         pr_info("mds%d caps renewed\n", session->s_mds);
864                         wake = 1;
865                 } else {
866                         pr_info("mds%d caps still stale\n", session->s_mds);
867                 }
868         }
869         dout("renewed_caps mds%d ttl now %lu, was %s, now %s\n",
870              session->s_mds, session->s_cap_ttl, was_stale ? "stale" : "fresh",
871              time_before(jiffies, session->s_cap_ttl) ? "stale" : "fresh");
872         spin_unlock(&session->s_cap_lock);
873
874         if (wake)
875                 wake_up_session_caps(session, 0);
876 }
877
878 /*
879  * send a session close request
880  */
881 static int request_close_session(struct ceph_mds_client *mdsc,
882                                  struct ceph_mds_session *session)
883 {
884         struct ceph_msg *msg;
885         int err = 0;
886
887         dout("request_close_session mds%d state %s seq %lld\n",
888              session->s_mds, session_state_name(session->s_state),
889              session->s_seq);
890         msg = create_session_msg(CEPH_SESSION_REQUEST_CLOSE, session->s_seq);
891         if (IS_ERR(msg))
892                 err = PTR_ERR(msg);
893         else
894                 ceph_con_send(&session->s_con, msg);
895         return err;
896 }
897
898 /*
899  * Called with s_mutex held.
900  */
901 static int __close_session(struct ceph_mds_client *mdsc,
902                          struct ceph_mds_session *session)
903 {
904         if (session->s_state >= CEPH_MDS_SESSION_CLOSING)
905                 return 0;
906         session->s_state = CEPH_MDS_SESSION_CLOSING;
907         return request_close_session(mdsc, session);
908 }
909
910 /*
911  * Trim old(er) caps.
912  *
913  * Because we can't cache an inode without one or more caps, we do
914  * this indirectly: if a cap is unused, we prune its aliases, at which
915  * point the inode will hopefully get dropped to.
916  *
917  * Yes, this is a bit sloppy.  Our only real goal here is to respond to
918  * memory pressure from the MDS, though, so it needn't be perfect.
919  */
920 static int trim_caps_cb(struct inode *inode, struct ceph_cap *cap, void *arg)
921 {
922         struct ceph_mds_session *session = arg;
923         struct ceph_inode_info *ci = ceph_inode(inode);
924         int used, oissued, mine;
925
926         if (session->s_trim_caps <= 0)
927                 return -1;
928
929         spin_lock(&inode->i_lock);
930         mine = cap->issued | cap->implemented;
931         used = __ceph_caps_used(ci);
932         oissued = __ceph_caps_issued_other(ci, cap);
933
934         dout("trim_caps_cb %p cap %p mine %s oissued %s used %s\n",
935              inode, cap, ceph_cap_string(mine), ceph_cap_string(oissued),
936              ceph_cap_string(used));
937         if (ci->i_dirty_caps)
938                 goto out;   /* dirty caps */
939         if ((used & ~oissued) & mine)
940                 goto out;   /* we need these caps */
941
942         session->s_trim_caps--;
943         if (oissued) {
944                 /* we aren't the only cap.. just remove us */
945                 __ceph_remove_cap(cap, NULL);
946         } else {
947                 /* try to drop referring dentries */
948                 spin_unlock(&inode->i_lock);
949                 d_prune_aliases(inode);
950                 dout("trim_caps_cb %p cap %p  pruned, count now %d\n",
951                      inode, cap, atomic_read(&inode->i_count));
952                 return 0;
953         }
954
955 out:
956         spin_unlock(&inode->i_lock);
957         return 0;
958 }
959
960 /*
961  * Trim session cap count down to some max number.
962  */
963 static int trim_caps(struct ceph_mds_client *mdsc,
964                      struct ceph_mds_session *session,
965                      int max_caps)
966 {
967         int trim_caps = session->s_nr_caps - max_caps;
968
969         dout("trim_caps mds%d start: %d / %d, trim %d\n",
970              session->s_mds, session->s_nr_caps, max_caps, trim_caps);
971         if (trim_caps > 0) {
972                 session->s_trim_caps = trim_caps;
973                 iterate_session_caps(session, trim_caps_cb, session);
974                 dout("trim_caps mds%d done: %d / %d, trimmed %d\n",
975                      session->s_mds, session->s_nr_caps, max_caps,
976                         trim_caps - session->s_trim_caps);
977                 session->s_trim_caps = 0;
978         }
979         return 0;
980 }
981
982 /*
983  * Allocate cap_release messages.  If there is a partially full message
984  * in the queue, try to allocate enough to cover it's remainder, so that
985  * we can send it immediately.
986  *
987  * Called under s_mutex.
988  */
989 static int add_cap_releases(struct ceph_mds_client *mdsc,
990                             struct ceph_mds_session *session,
991                             int extra)
992 {
993         struct ceph_msg *msg;
994         struct ceph_mds_cap_release *head;
995         int err = -ENOMEM;
996
997         if (extra < 0)
998                 extra = mdsc->client->mount_args->cap_release_safety;
999
1000         spin_lock(&session->s_cap_lock);
1001
1002         if (!list_empty(&session->s_cap_releases)) {
1003                 msg = list_first_entry(&session->s_cap_releases,
1004                                        struct ceph_msg,
1005                                  list_head);
1006                 head = msg->front.iov_base;
1007                 extra += CEPH_CAPS_PER_RELEASE - le32_to_cpu(head->num);
1008         }
1009
1010         while (session->s_num_cap_releases < session->s_nr_caps + extra) {
1011                 spin_unlock(&session->s_cap_lock);
1012                 msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPRELEASE, PAGE_CACHE_SIZE,
1013                                    0, 0, NULL);
1014                 if (!msg)
1015                         goto out_unlocked;
1016                 dout("add_cap_releases %p msg %p now %d\n", session, msg,
1017                      (int)msg->front.iov_len);
1018                 head = msg->front.iov_base;
1019                 head->num = cpu_to_le32(0);
1020                 msg->front.iov_len = sizeof(*head);
1021                 spin_lock(&session->s_cap_lock);
1022                 list_add(&msg->list_head, &session->s_cap_releases);
1023                 session->s_num_cap_releases += CEPH_CAPS_PER_RELEASE;
1024         }
1025
1026         if (!list_empty(&session->s_cap_releases)) {
1027                 msg = list_first_entry(&session->s_cap_releases,
1028                                        struct ceph_msg,
1029                                        list_head);
1030                 head = msg->front.iov_base;
1031                 if (head->num) {
1032                         dout(" queueing non-full %p (%d)\n", msg,
1033                              le32_to_cpu(head->num));
1034                         list_move_tail(&msg->list_head,
1035                                       &session->s_cap_releases_done);
1036                         session->s_num_cap_releases -=
1037                                 CEPH_CAPS_PER_RELEASE - le32_to_cpu(head->num);
1038                 }
1039         }
1040         err = 0;
1041         spin_unlock(&session->s_cap_lock);
1042 out_unlocked:
1043         return err;
1044 }
1045
1046 /*
1047  * flush all dirty inode data to disk.
1048  *
1049  * returns true if we've flushed through want_flush_seq
1050  */
1051 static int check_cap_flush(struct ceph_mds_client *mdsc, u64 want_flush_seq)
1052 {
1053         int mds, ret = 1;
1054
1055         dout("check_cap_flush want %lld\n", want_flush_seq);
1056         mutex_lock(&mdsc->mutex);
1057         for (mds = 0; ret && mds < mdsc->max_sessions; mds++) {
1058                 struct ceph_mds_session *session = mdsc->sessions[mds];
1059
1060                 if (!session)
1061                         continue;
1062                 get_session(session);
1063                 mutex_unlock(&mdsc->mutex);
1064
1065                 mutex_lock(&session->s_mutex);
1066                 if (!list_empty(&session->s_cap_flushing)) {
1067                         struct ceph_inode_info *ci =
1068                                 list_entry(session->s_cap_flushing.next,
1069                                            struct ceph_inode_info,
1070                                            i_flushing_item);
1071                         struct inode *inode = &ci->vfs_inode;
1072
1073                         spin_lock(&inode->i_lock);
1074                         if (ci->i_cap_flush_seq <= want_flush_seq) {
1075                                 dout("check_cap_flush still flushing %p "
1076                                      "seq %lld <= %lld to mds%d\n", inode,
1077                                      ci->i_cap_flush_seq, want_flush_seq,
1078                                      session->s_mds);
1079                                 ret = 0;
1080                         }
1081                         spin_unlock(&inode->i_lock);
1082                 }
1083                 mutex_unlock(&session->s_mutex);
1084                 ceph_put_mds_session(session);
1085
1086                 if (!ret)
1087                         return ret;
1088                 mutex_lock(&mdsc->mutex);
1089         }
1090
1091         mutex_unlock(&mdsc->mutex);
1092         dout("check_cap_flush ok, flushed thru %lld\n", want_flush_seq);
1093         return ret;
1094 }
1095
1096 /*
1097  * called under s_mutex
1098  */
1099 static void send_cap_releases(struct ceph_mds_client *mdsc,
1100                        struct ceph_mds_session *session)
1101 {
1102         struct ceph_msg *msg;
1103
1104         dout("send_cap_releases mds%d\n", session->s_mds);
1105         while (1) {
1106                 spin_lock(&session->s_cap_lock);
1107                 if (list_empty(&session->s_cap_releases_done))
1108                         break;
1109                 msg = list_first_entry(&session->s_cap_releases_done,
1110                                  struct ceph_msg, list_head);
1111                 list_del_init(&msg->list_head);
1112                 spin_unlock(&session->s_cap_lock);
1113                 msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1114                 dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1115                 ceph_con_send(&session->s_con, msg);
1116         }
1117         spin_unlock(&session->s_cap_lock);
1118 }
1119
1120 /*
1121  * requests
1122  */
1123
1124 /*
1125  * Create an mds request.
1126  */
1127 struct ceph_mds_request *
1128 ceph_mdsc_create_request(struct ceph_mds_client *mdsc, int op, int mode)
1129 {
1130         struct ceph_mds_request *req = kzalloc(sizeof(*req), GFP_NOFS);
1131
1132         if (!req)
1133                 return ERR_PTR(-ENOMEM);
1134
1135         req->r_started = jiffies;
1136         req->r_resend_mds = -1;
1137         INIT_LIST_HEAD(&req->r_unsafe_dir_item);
1138         req->r_fmode = -1;
1139         kref_init(&req->r_kref);
1140         INIT_LIST_HEAD(&req->r_wait);
1141         init_completion(&req->r_completion);
1142         init_completion(&req->r_safe_completion);
1143         INIT_LIST_HEAD(&req->r_unsafe_item);
1144
1145         req->r_op = op;
1146         req->r_direct_mode = mode;
1147         return req;
1148 }
1149
1150 /*
1151  * return oldest (lowest) request, tid in request tree, 0 if none.
1152  *
1153  * called under mdsc->mutex.
1154  */
1155 static struct ceph_mds_request *__get_oldest_req(struct ceph_mds_client *mdsc)
1156 {
1157         if (RB_EMPTY_ROOT(&mdsc->request_tree))
1158                 return NULL;
1159         return rb_entry(rb_first(&mdsc->request_tree),
1160                         struct ceph_mds_request, r_node);
1161 }
1162
1163 static u64 __get_oldest_tid(struct ceph_mds_client *mdsc)
1164 {
1165         struct ceph_mds_request *req = __get_oldest_req(mdsc);
1166
1167         if (req)
1168                 return req->r_tid;
1169         return 0;
1170 }
1171
1172 /*
1173  * Build a dentry's path.  Allocate on heap; caller must kfree.  Based
1174  * on build_path_from_dentry in fs/cifs/dir.c.
1175  *
1176  * If @stop_on_nosnap, generate path relative to the first non-snapped
1177  * inode.
1178  *
1179  * Encode hidden .snap dirs as a double /, i.e.
1180  *   foo/.snap/bar -> foo//bar
1181  */
1182 char *ceph_mdsc_build_path(struct dentry *dentry, int *plen, u64 *base,
1183                            int stop_on_nosnap)
1184 {
1185         struct dentry *temp;
1186         char *path;
1187         int len, pos;
1188
1189         if (dentry == NULL)
1190                 return ERR_PTR(-EINVAL);
1191
1192 retry:
1193         len = 0;
1194         for (temp = dentry; !IS_ROOT(temp);) {
1195                 struct inode *inode = temp->d_inode;
1196                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR)
1197                         len++;  /* slash only */
1198                 else if (stop_on_nosnap && inode &&
1199                          ceph_snap(inode) == CEPH_NOSNAP)
1200                         break;
1201                 else
1202                         len += 1 + temp->d_name.len;
1203                 temp = temp->d_parent;
1204                 if (temp == NULL) {
1205                         pr_err("build_path_dentry corrupt dentry %p\n", dentry);
1206                         return ERR_PTR(-EINVAL);
1207                 }
1208         }
1209         if (len)
1210                 len--;  /* no leading '/' */
1211
1212         path = kmalloc(len+1, GFP_NOFS);
1213         if (path == NULL)
1214                 return ERR_PTR(-ENOMEM);
1215         pos = len;
1216         path[pos] = 0;  /* trailing null */
1217         for (temp = dentry; !IS_ROOT(temp) && pos != 0; ) {
1218                 struct inode *inode = temp->d_inode;
1219
1220                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
1221                         dout("build_path_dentry path+%d: %p SNAPDIR\n",
1222                              pos, temp);
1223                 } else if (stop_on_nosnap && inode &&
1224                            ceph_snap(inode) == CEPH_NOSNAP) {
1225                         break;
1226                 } else {
1227                         pos -= temp->d_name.len;
1228                         if (pos < 0)
1229                                 break;
1230                         strncpy(path + pos, temp->d_name.name,
1231                                 temp->d_name.len);
1232                         dout("build_path_dentry path+%d: %p '%.*s'\n",
1233                              pos, temp, temp->d_name.len, path + pos);
1234                 }
1235                 if (pos)
1236                         path[--pos] = '/';
1237                 temp = temp->d_parent;
1238                 if (temp == NULL) {
1239                         pr_err("build_path_dentry corrupt dentry\n");
1240                         kfree(path);
1241                         return ERR_PTR(-EINVAL);
1242                 }
1243         }
1244         if (pos != 0) {
1245                 pr_err("build_path_dentry did not end path lookup where "
1246                        "expected, namelen is %d, pos is %d\n", len, pos);
1247                 /* presumably this is only possible if racing with a
1248                    rename of one of the parent directories (we can not
1249                    lock the dentries above us to prevent this, but
1250                    retrying should be harmless) */
1251                 kfree(path);
1252                 goto retry;
1253         }
1254
1255         *base = ceph_ino(temp->d_inode);
1256         *plen = len;
1257         dout("build_path_dentry on %p %d built %llx '%.*s'\n",
1258              dentry, atomic_read(&dentry->d_count), *base, len, path);
1259         return path;
1260 }
1261
1262 static int build_dentry_path(struct dentry *dentry,
1263                              const char **ppath, int *ppathlen, u64 *pino,
1264                              int *pfreepath)
1265 {
1266         char *path;
1267
1268         if (ceph_snap(dentry->d_parent->d_inode) == CEPH_NOSNAP) {
1269                 *pino = ceph_ino(dentry->d_parent->d_inode);
1270                 *ppath = dentry->d_name.name;
1271                 *ppathlen = dentry->d_name.len;
1272                 return 0;
1273         }
1274         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1275         if (IS_ERR(path))
1276                 return PTR_ERR(path);
1277         *ppath = path;
1278         *pfreepath = 1;
1279         return 0;
1280 }
1281
1282 static int build_inode_path(struct inode *inode,
1283                             const char **ppath, int *ppathlen, u64 *pino,
1284                             int *pfreepath)
1285 {
1286         struct dentry *dentry;
1287         char *path;
1288
1289         if (ceph_snap(inode) == CEPH_NOSNAP) {
1290                 *pino = ceph_ino(inode);
1291                 *ppathlen = 0;
1292                 return 0;
1293         }
1294         dentry = d_find_alias(inode);
1295         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1296         dput(dentry);
1297         if (IS_ERR(path))
1298                 return PTR_ERR(path);
1299         *ppath = path;
1300         *pfreepath = 1;
1301         return 0;
1302 }
1303
1304 /*
1305  * request arguments may be specified via an inode *, a dentry *, or
1306  * an explicit ino+path.
1307  */
1308 static int set_request_path_attr(struct inode *rinode, struct dentry *rdentry,
1309                                   const char *rpath, u64 rino,
1310                                   const char **ppath, int *pathlen,
1311                                   u64 *ino, int *freepath)
1312 {
1313         int r = 0;
1314
1315         if (rinode) {
1316                 r = build_inode_path(rinode, ppath, pathlen, ino, freepath);
1317                 dout(" inode %p %llx.%llx\n", rinode, ceph_ino(rinode),
1318                      ceph_snap(rinode));
1319         } else if (rdentry) {
1320                 r = build_dentry_path(rdentry, ppath, pathlen, ino, freepath);
1321                 dout(" dentry %p %llx/%.*s\n", rdentry, *ino, *pathlen,
1322                      *ppath);
1323         } else if (rpath) {
1324                 *ino = rino;
1325                 *ppath = rpath;
1326                 *pathlen = strlen(rpath);
1327                 dout(" path %.*s\n", *pathlen, rpath);
1328         }
1329
1330         return r;
1331 }
1332
1333 /*
1334  * called under mdsc->mutex
1335  */
1336 static struct ceph_msg *create_request_message(struct ceph_mds_client *mdsc,
1337                                                struct ceph_mds_request *req,
1338                                                int mds)
1339 {
1340         struct ceph_msg *msg;
1341         struct ceph_mds_request_head *head;
1342         const char *path1 = NULL;
1343         const char *path2 = NULL;
1344         u64 ino1 = 0, ino2 = 0;
1345         int pathlen1 = 0, pathlen2 = 0;
1346         int freepath1 = 0, freepath2 = 0;
1347         int len;
1348         u16 releases;
1349         void *p, *end;
1350         int ret;
1351
1352         ret = set_request_path_attr(req->r_inode, req->r_dentry,
1353                               req->r_path1, req->r_ino1.ino,
1354                               &path1, &pathlen1, &ino1, &freepath1);
1355         if (ret < 0) {
1356                 msg = ERR_PTR(ret);
1357                 goto out;
1358         }
1359
1360         ret = set_request_path_attr(NULL, req->r_old_dentry,
1361                               req->r_path2, req->r_ino2.ino,
1362                               &path2, &pathlen2, &ino2, &freepath2);
1363         if (ret < 0) {
1364                 msg = ERR_PTR(ret);
1365                 goto out_free1;
1366         }
1367
1368         len = sizeof(*head) +
1369                 pathlen1 + pathlen2 + 2*(1 + sizeof(u32) + sizeof(u64));
1370
1371         /* calculate (max) length for cap releases */
1372         len += sizeof(struct ceph_mds_request_release) *
1373                 (!!req->r_inode_drop + !!req->r_dentry_drop +
1374                  !!req->r_old_inode_drop + !!req->r_old_dentry_drop);
1375         if (req->r_dentry_drop)
1376                 len += req->r_dentry->d_name.len;
1377         if (req->r_old_dentry_drop)
1378                 len += req->r_old_dentry->d_name.len;
1379
1380         msg = ceph_msg_new(CEPH_MSG_CLIENT_REQUEST, len, 0, 0, NULL);
1381         if (IS_ERR(msg))
1382                 goto out_free2;
1383
1384         msg->hdr.tid = cpu_to_le64(req->r_tid);
1385
1386         head = msg->front.iov_base;
1387         p = msg->front.iov_base + sizeof(*head);
1388         end = msg->front.iov_base + msg->front.iov_len;
1389
1390         head->mdsmap_epoch = cpu_to_le32(mdsc->mdsmap->m_epoch);
1391         head->op = cpu_to_le32(req->r_op);
1392         head->caller_uid = cpu_to_le32(current_fsuid());
1393         head->caller_gid = cpu_to_le32(current_fsgid());
1394         head->args = req->r_args;
1395
1396         ceph_encode_filepath(&p, end, ino1, path1);
1397         ceph_encode_filepath(&p, end, ino2, path2);
1398
1399         /* cap releases */
1400         releases = 0;
1401         if (req->r_inode_drop)
1402                 releases += ceph_encode_inode_release(&p,
1403                       req->r_inode ? req->r_inode : req->r_dentry->d_inode,
1404                       mds, req->r_inode_drop, req->r_inode_unless, 0);
1405         if (req->r_dentry_drop)
1406                 releases += ceph_encode_dentry_release(&p, req->r_dentry,
1407                        mds, req->r_dentry_drop, req->r_dentry_unless);
1408         if (req->r_old_dentry_drop)
1409                 releases += ceph_encode_dentry_release(&p, req->r_old_dentry,
1410                        mds, req->r_old_dentry_drop, req->r_old_dentry_unless);
1411         if (req->r_old_inode_drop)
1412                 releases += ceph_encode_inode_release(&p,
1413                       req->r_old_dentry->d_inode,
1414                       mds, req->r_old_inode_drop, req->r_old_inode_unless, 0);
1415         head->num_releases = cpu_to_le16(releases);
1416
1417         BUG_ON(p > end);
1418         msg->front.iov_len = p - msg->front.iov_base;
1419         msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1420
1421         msg->pages = req->r_pages;
1422         msg->nr_pages = req->r_num_pages;
1423         msg->hdr.data_len = cpu_to_le32(req->r_data_len);
1424         msg->hdr.data_off = cpu_to_le16(0);
1425
1426 out_free2:
1427         if (freepath2)
1428                 kfree((char *)path2);
1429 out_free1:
1430         if (freepath1)
1431                 kfree((char *)path1);
1432 out:
1433         return msg;
1434 }
1435
1436 /*
1437  * called under mdsc->mutex if error, under no mutex if
1438  * success.
1439  */
1440 static void complete_request(struct ceph_mds_client *mdsc,
1441                              struct ceph_mds_request *req)
1442 {
1443         if (req->r_callback)
1444                 req->r_callback(mdsc, req);
1445         else
1446                 complete(&req->r_completion);
1447 }
1448
1449 /*
1450  * called under mdsc->mutex
1451  */
1452 static int __prepare_send_request(struct ceph_mds_client *mdsc,
1453                                   struct ceph_mds_request *req,
1454                                   int mds)
1455 {
1456         struct ceph_mds_request_head *rhead;
1457         struct ceph_msg *msg;
1458         int flags = 0;
1459
1460         req->r_mds = mds;
1461         req->r_attempts++;
1462         dout("prepare_send_request %p tid %lld %s (attempt %d)\n", req,
1463              req->r_tid, ceph_mds_op_name(req->r_op), req->r_attempts);
1464
1465         if (req->r_request) {
1466                 ceph_msg_put(req->r_request);
1467                 req->r_request = NULL;
1468         }
1469         msg = create_request_message(mdsc, req, mds);
1470         if (IS_ERR(msg)) {
1471                 req->r_reply = ERR_PTR(PTR_ERR(msg));
1472                 complete_request(mdsc, req);
1473                 return -PTR_ERR(msg);
1474         }
1475         req->r_request = msg;
1476
1477         rhead = msg->front.iov_base;
1478         rhead->oldest_client_tid = cpu_to_le64(__get_oldest_tid(mdsc));
1479         if (req->r_got_unsafe)
1480                 flags |= CEPH_MDS_FLAG_REPLAY;
1481         if (req->r_locked_dir)
1482                 flags |= CEPH_MDS_FLAG_WANT_DENTRY;
1483         rhead->flags = cpu_to_le32(flags);
1484         rhead->num_fwd = req->r_num_fwd;
1485         rhead->num_retry = req->r_attempts - 1;
1486
1487         dout(" r_locked_dir = %p\n", req->r_locked_dir);
1488
1489         if (req->r_target_inode && req->r_got_unsafe)
1490                 rhead->ino = cpu_to_le64(ceph_ino(req->r_target_inode));
1491         else
1492                 rhead->ino = 0;
1493         return 0;
1494 }
1495
1496 /*
1497  * send request, or put it on the appropriate wait list.
1498  */
1499 static int __do_request(struct ceph_mds_client *mdsc,
1500                         struct ceph_mds_request *req)
1501 {
1502         struct ceph_mds_session *session = NULL;
1503         int mds = -1;
1504         int err = -EAGAIN;
1505
1506         if (req->r_reply)
1507                 goto out;
1508
1509         if (req->r_timeout &&
1510             time_after_eq(jiffies, req->r_started + req->r_timeout)) {
1511                 dout("do_request timed out\n");
1512                 err = -EIO;
1513                 goto finish;
1514         }
1515
1516         mds = __choose_mds(mdsc, req);
1517         if (mds < 0 ||
1518             ceph_mdsmap_get_state(mdsc->mdsmap, mds) < CEPH_MDS_STATE_ACTIVE) {
1519                 dout("do_request no mds or not active, waiting for map\n");
1520                 list_add(&req->r_wait, &mdsc->waiting_for_map);
1521                 goto out;
1522         }
1523
1524         /* get, open session */
1525         session = __ceph_lookup_mds_session(mdsc, mds);
1526         if (!session)
1527                 session = register_session(mdsc, mds);
1528         dout("do_request mds%d session %p state %s\n", mds, session,
1529              session_state_name(session->s_state));
1530         if (session->s_state != CEPH_MDS_SESSION_OPEN &&
1531             session->s_state != CEPH_MDS_SESSION_HUNG) {
1532                 if (session->s_state == CEPH_MDS_SESSION_NEW ||
1533                     session->s_state == CEPH_MDS_SESSION_CLOSING)
1534                         __open_session(mdsc, session);
1535                 list_add(&req->r_wait, &session->s_waiting);
1536                 goto out_session;
1537         }
1538
1539         /* send request */
1540         req->r_session = get_session(session);
1541         req->r_resend_mds = -1;   /* forget any previous mds hint */
1542
1543         if (req->r_request_started == 0)   /* note request start time */
1544                 req->r_request_started = jiffies;
1545
1546         err = __prepare_send_request(mdsc, req, mds);
1547         if (!err) {
1548                 ceph_msg_get(req->r_request);
1549                 ceph_con_send(&session->s_con, req->r_request);
1550         }
1551
1552 out_session:
1553         ceph_put_mds_session(session);
1554 out:
1555         return err;
1556
1557 finish:
1558         req->r_reply = ERR_PTR(err);
1559         complete_request(mdsc, req);
1560         goto out;
1561 }
1562
1563 /*
1564  * called under mdsc->mutex
1565  */
1566 static void __wake_requests(struct ceph_mds_client *mdsc,
1567                             struct list_head *head)
1568 {
1569         struct ceph_mds_request *req, *nreq;
1570
1571         list_for_each_entry_safe(req, nreq, head, r_wait) {
1572                 list_del_init(&req->r_wait);
1573                 __do_request(mdsc, req);
1574         }
1575 }
1576
1577 /*
1578  * Wake up threads with requests pending for @mds, so that they can
1579  * resubmit their requests to a possibly different mds.  If @all is set,
1580  * wake up if their requests has been forwarded to @mds, too.
1581  */
1582 static void kick_requests(struct ceph_mds_client *mdsc, int mds, int all)
1583 {
1584         struct ceph_mds_request *req;
1585         struct rb_node *p;
1586
1587         dout("kick_requests mds%d\n", mds);
1588         for (p = rb_first(&mdsc->request_tree); p; p = rb_next(p)) {
1589                 req = rb_entry(p, struct ceph_mds_request, r_node);
1590                 if (req->r_got_unsafe)
1591                         continue;
1592                 if (req->r_session &&
1593                     req->r_session->s_mds == mds) {
1594                         dout(" kicking tid %llu\n", req->r_tid);
1595                         put_request_session(req);
1596                         __do_request(mdsc, req);
1597                 }
1598         }
1599 }
1600
1601 void ceph_mdsc_submit_request(struct ceph_mds_client *mdsc,
1602                               struct ceph_mds_request *req)
1603 {
1604         dout("submit_request on %p\n", req);
1605         mutex_lock(&mdsc->mutex);
1606         __register_request(mdsc, req, NULL);
1607         __do_request(mdsc, req);
1608         mutex_unlock(&mdsc->mutex);
1609 }
1610
1611 /*
1612  * Synchrously perform an mds request.  Take care of all of the
1613  * session setup, forwarding, retry details.
1614  */
1615 int ceph_mdsc_do_request(struct ceph_mds_client *mdsc,
1616                          struct inode *dir,
1617                          struct ceph_mds_request *req)
1618 {
1619         int err;
1620
1621         dout("do_request on %p\n", req);
1622
1623         /* take CAP_PIN refs for r_inode, r_locked_dir, r_old_dentry */
1624         if (req->r_inode)
1625                 ceph_get_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
1626         if (req->r_locked_dir)
1627                 ceph_get_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
1628         if (req->r_old_dentry)
1629                 ceph_get_cap_refs(
1630                         ceph_inode(req->r_old_dentry->d_parent->d_inode),
1631                         CEPH_CAP_PIN);
1632
1633         /* issue */
1634         mutex_lock(&mdsc->mutex);
1635         __register_request(mdsc, req, dir);
1636         __do_request(mdsc, req);
1637
1638         /* wait */
1639         if (!req->r_reply) {
1640                 mutex_unlock(&mdsc->mutex);
1641                 if (req->r_timeout) {
1642                         err = (long)wait_for_completion_interruptible_timeout(
1643                                 &req->r_completion, req->r_timeout);
1644                         if (err == 0)
1645                                 req->r_reply = ERR_PTR(-EIO);
1646                         else if (err < 0)
1647                                 req->r_reply = ERR_PTR(err);
1648                 } else {
1649                         err = wait_for_completion_interruptible(
1650                                 &req->r_completion);
1651                         if (err)
1652                                 req->r_reply = ERR_PTR(err);
1653                 }
1654                 mutex_lock(&mdsc->mutex);
1655         }
1656
1657         if (IS_ERR(req->r_reply)) {
1658                 err = PTR_ERR(req->r_reply);
1659                 req->r_reply = NULL;
1660
1661                 if (err == -ERESTARTSYS) {
1662                         /* aborted */
1663                         req->r_aborted = true;
1664
1665                         if (req->r_locked_dir &&
1666                             (req->r_op & CEPH_MDS_OP_WRITE)) {
1667                                 struct ceph_inode_info *ci =
1668                                         ceph_inode(req->r_locked_dir);
1669
1670                                 dout("aborted, clearing I_COMPLETE on %p\n", 
1671                                      req->r_locked_dir);
1672                                 spin_lock(&req->r_locked_dir->i_lock);
1673                                 ci->i_ceph_flags &= ~CEPH_I_COMPLETE;
1674                                 ci->i_release_count++;
1675                                 spin_unlock(&req->r_locked_dir->i_lock);
1676                         }
1677                 } else {
1678                         /* clean up this request */
1679                         __unregister_request(mdsc, req);
1680                         if (!list_empty(&req->r_unsafe_item))
1681                                 list_del_init(&req->r_unsafe_item);
1682                         complete(&req->r_safe_completion);
1683                 }
1684         } else if (req->r_err) {
1685                 err = req->r_err;
1686         } else {
1687                 err = le32_to_cpu(req->r_reply_info.head->result);
1688         }
1689         mutex_unlock(&mdsc->mutex);
1690
1691         dout("do_request %p done, result %d\n", req, err);
1692         return err;
1693 }
1694
1695 /*
1696  * Handle mds reply.
1697  *
1698  * We take the session mutex and parse and process the reply immediately.
1699  * This preserves the logical ordering of replies, capabilities, etc., sent
1700  * by the MDS as they are applied to our local cache.
1701  */
1702 static void handle_reply(struct ceph_mds_session *session, struct ceph_msg *msg)
1703 {
1704         struct ceph_mds_client *mdsc = session->s_mdsc;
1705         struct ceph_mds_request *req;
1706         struct ceph_mds_reply_head *head = msg->front.iov_base;
1707         struct ceph_mds_reply_info_parsed *rinfo;  /* parsed reply info */
1708         u64 tid;
1709         int err, result;
1710         int mds;
1711
1712         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1713                 return;
1714         if (msg->front.iov_len < sizeof(*head)) {
1715                 pr_err("mdsc_handle_reply got corrupt (short) reply\n");
1716                 ceph_msg_dump(msg);
1717                 return;
1718         }
1719
1720         /* get request, session */
1721         tid = le64_to_cpu(msg->hdr.tid);
1722         mutex_lock(&mdsc->mutex);
1723         req = __lookup_request(mdsc, tid);
1724         if (!req) {
1725                 dout("handle_reply on unknown tid %llu\n", tid);
1726                 mutex_unlock(&mdsc->mutex);
1727                 return;
1728         }
1729         dout("handle_reply %p\n", req);
1730         mds = le64_to_cpu(msg->hdr.src.name.num);
1731
1732         /* correct session? */
1733         if (!req->r_session && req->r_session != session) {
1734                 pr_err("mdsc_handle_reply got %llu on session mds%d"
1735                        " not mds%d\n", tid, session->s_mds,
1736                        req->r_session ? req->r_session->s_mds : -1);
1737                 mutex_unlock(&mdsc->mutex);
1738                 goto out;
1739         }
1740
1741         /* dup? */
1742         if ((req->r_got_unsafe && !head->safe) ||
1743             (req->r_got_safe && head->safe)) {
1744                 pr_warning("got a dup %s reply on %llu from mds%d\n",
1745                            head->safe ? "safe" : "unsafe", tid, mds);
1746                 mutex_unlock(&mdsc->mutex);
1747                 goto out;
1748         }
1749
1750         result = le32_to_cpu(head->result);
1751
1752         /*
1753          * Tolerate 2 consecutive ESTALEs from the same mds.
1754          * FIXME: we should be looking at the cap migrate_seq.
1755          */
1756         if (result == -ESTALE) {
1757                 req->r_direct_mode = USE_AUTH_MDS;
1758                 req->r_num_stale++;
1759                 if (req->r_num_stale <= 2) {
1760                         __do_request(mdsc, req);
1761                         mutex_unlock(&mdsc->mutex);
1762                         goto out;
1763                 }
1764         } else {
1765                 req->r_num_stale = 0;
1766         }
1767
1768         if (head->safe) {
1769                 req->r_got_safe = true;
1770                 __unregister_request(mdsc, req);
1771                 complete(&req->r_safe_completion);
1772
1773                 if (req->r_got_unsafe) {
1774                         /*
1775                          * We already handled the unsafe response, now do the
1776                          * cleanup.  No need to examine the response; the MDS
1777                          * doesn't include any result info in the safe
1778                          * response.  And even if it did, there is nothing
1779                          * useful we could do with a revised return value.
1780                          */
1781                         dout("got safe reply %llu, mds%d\n", tid, mds);
1782                         list_del_init(&req->r_unsafe_item);
1783
1784                         /* last unsafe request during umount? */
1785                         if (mdsc->stopping && !__get_oldest_req(mdsc))
1786                                 complete(&mdsc->safe_umount_waiters);
1787                         mutex_unlock(&mdsc->mutex);
1788                         goto out;
1789                 }
1790         }
1791
1792         BUG_ON(req->r_reply);
1793
1794         if (!head->safe) {
1795                 req->r_got_unsafe = true;
1796                 list_add_tail(&req->r_unsafe_item, &req->r_session->s_unsafe);
1797         }
1798
1799         dout("handle_reply tid %lld result %d\n", tid, result);
1800         rinfo = &req->r_reply_info;
1801         err = parse_reply_info(msg, rinfo);
1802         mutex_unlock(&mdsc->mutex);
1803
1804         mutex_lock(&session->s_mutex);
1805         if (err < 0) {
1806                 pr_err("mdsc_handle_reply got corrupt reply mds%d\n", mds);
1807                 ceph_msg_dump(msg);
1808                 goto out_err;
1809         }
1810
1811         /* snap trace */
1812         if (rinfo->snapblob_len) {
1813                 down_write(&mdsc->snap_rwsem);
1814                 ceph_update_snap_trace(mdsc, rinfo->snapblob,
1815                                rinfo->snapblob + rinfo->snapblob_len,
1816                                le32_to_cpu(head->op) == CEPH_MDS_OP_RMSNAP);
1817                 downgrade_write(&mdsc->snap_rwsem);
1818         } else {
1819                 down_read(&mdsc->snap_rwsem);
1820         }
1821
1822         /* insert trace into our cache */
1823         err = ceph_fill_trace(mdsc->client->sb, req, req->r_session);
1824         if (err == 0) {
1825                 if (result == 0 && rinfo->dir_nr)
1826                         ceph_readdir_prepopulate(req, req->r_session);
1827                 ceph_unreserve_caps(&req->r_caps_reservation);
1828         }
1829
1830         up_read(&mdsc->snap_rwsem);
1831 out_err:
1832         if (err) {
1833                 req->r_err = err;
1834         } else {
1835                 req->r_reply = msg;
1836                 ceph_msg_get(msg);
1837         }
1838
1839         add_cap_releases(mdsc, req->r_session, -1);
1840         mutex_unlock(&session->s_mutex);
1841
1842         /* kick calling process */
1843         complete_request(mdsc, req);
1844 out:
1845         ceph_mdsc_put_request(req);
1846         return;
1847 }
1848
1849
1850
1851 /*
1852  * handle mds notification that our request has been forwarded.
1853  */
1854 static void handle_forward(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
1855 {
1856         struct ceph_mds_request *req;
1857         u64 tid;
1858         u32 next_mds;
1859         u32 fwd_seq;
1860         u8 must_resend;
1861         int err = -EINVAL;
1862         void *p = msg->front.iov_base;
1863         void *end = p + msg->front.iov_len;
1864         int from_mds, state;
1865
1866         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1867                 goto bad;
1868         from_mds = le64_to_cpu(msg->hdr.src.name.num);
1869
1870         ceph_decode_need(&p, end, sizeof(u64)+2*sizeof(u32), bad);
1871         tid = ceph_decode_64(&p);
1872         next_mds = ceph_decode_32(&p);
1873         fwd_seq = ceph_decode_32(&p);
1874         must_resend = ceph_decode_8(&p);
1875
1876         WARN_ON(must_resend);  /* shouldn't happen. */
1877
1878         mutex_lock(&mdsc->mutex);
1879         req = __lookup_request(mdsc, tid);
1880         if (!req) {
1881                 dout("forward %llu dne\n", tid);
1882                 goto out;  /* dup reply? */
1883         }
1884
1885         state = mdsc->sessions[next_mds]->s_state;
1886         if (fwd_seq <= req->r_num_fwd) {
1887                 dout("forward %llu to mds%d - old seq %d <= %d\n",
1888                      tid, next_mds, req->r_num_fwd, fwd_seq);
1889         } else {
1890                 /* resend. forward race not possible; mds would drop */
1891                 dout("forward %llu to mds%d (we resend)\n", tid, next_mds);
1892                 req->r_num_fwd = fwd_seq;
1893                 req->r_resend_mds = next_mds;
1894                 put_request_session(req);
1895                 __do_request(mdsc, req);
1896         }
1897         ceph_mdsc_put_request(req);
1898 out:
1899         mutex_unlock(&mdsc->mutex);
1900         return;
1901
1902 bad:
1903         pr_err("mdsc_handle_forward decode error err=%d\n", err);
1904 }
1905
1906 /*
1907  * handle a mds session control message
1908  */
1909 static void handle_session(struct ceph_mds_session *session,
1910                            struct ceph_msg *msg)
1911 {
1912         struct ceph_mds_client *mdsc = session->s_mdsc;
1913         u32 op;
1914         u64 seq;
1915         int mds;
1916         struct ceph_mds_session_head *h = msg->front.iov_base;
1917         int wake = 0;
1918
1919         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1920                 return;
1921         mds = le64_to_cpu(msg->hdr.src.name.num);
1922
1923         /* decode */
1924         if (msg->front.iov_len != sizeof(*h))
1925                 goto bad;
1926         op = le32_to_cpu(h->op);
1927         seq = le64_to_cpu(h->seq);
1928
1929         mutex_lock(&mdsc->mutex);
1930         /* FIXME: this ttl calculation is generous */
1931         session->s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose;
1932         mutex_unlock(&mdsc->mutex);
1933
1934         mutex_lock(&session->s_mutex);
1935
1936         dout("handle_session mds%d %s %p state %s seq %llu\n",
1937              mds, ceph_session_op_name(op), session,
1938              session_state_name(session->s_state), seq);
1939
1940         if (session->s_state == CEPH_MDS_SESSION_HUNG) {
1941                 session->s_state = CEPH_MDS_SESSION_OPEN;
1942                 pr_info("mds%d came back\n", session->s_mds);
1943         }
1944
1945         switch (op) {
1946         case CEPH_SESSION_OPEN:
1947                 session->s_state = CEPH_MDS_SESSION_OPEN;
1948                 renewed_caps(mdsc, session, 0);
1949                 wake = 1;
1950                 if (mdsc->stopping)
1951                         __close_session(mdsc, session);
1952                 break;
1953
1954         case CEPH_SESSION_RENEWCAPS:
1955                 if (session->s_renew_seq == seq)
1956                         renewed_caps(mdsc, session, 1);
1957                 break;
1958
1959         case CEPH_SESSION_CLOSE:
1960                 unregister_session(mdsc, session);
1961                 remove_session_caps(session);
1962                 wake = 1; /* for good measure */
1963                 complete(&mdsc->session_close_waiters);
1964                 kick_requests(mdsc, mds, 0);      /* cur only */
1965                 break;
1966
1967         case CEPH_SESSION_STALE:
1968                 pr_info("mds%d caps went stale, renewing\n",
1969                         session->s_mds);
1970                 spin_lock(&session->s_cap_lock);
1971                 session->s_cap_gen++;
1972                 session->s_cap_ttl = 0;
1973                 spin_unlock(&session->s_cap_lock);
1974                 send_renew_caps(mdsc, session);
1975                 break;
1976
1977         case CEPH_SESSION_RECALL_STATE:
1978                 trim_caps(mdsc, session, le32_to_cpu(h->max_caps));
1979                 break;
1980
1981         default:
1982                 pr_err("mdsc_handle_session bad op %d mds%d\n", op, mds);
1983                 WARN_ON(1);
1984         }
1985
1986         mutex_unlock(&session->s_mutex);
1987         if (wake) {
1988                 mutex_lock(&mdsc->mutex);
1989                 __wake_requests(mdsc, &session->s_waiting);
1990                 mutex_unlock(&mdsc->mutex);
1991         }
1992         return;
1993
1994 bad:
1995         pr_err("mdsc_handle_session corrupt message mds%d len %d\n", mds,
1996                (int)msg->front.iov_len);
1997         ceph_msg_dump(msg);
1998         return;
1999 }
2000
2001
2002 /*
2003  * called under session->mutex.
2004  */
2005 static void replay_unsafe_requests(struct ceph_mds_client *mdsc,
2006                                    struct ceph_mds_session *session)
2007 {
2008         struct ceph_mds_request *req, *nreq;
2009         int err;
2010
2011         dout("replay_unsafe_requests mds%d\n", session->s_mds);
2012
2013         mutex_lock(&mdsc->mutex);
2014         list_for_each_entry_safe(req, nreq, &session->s_unsafe, r_unsafe_item) {
2015                 err = __prepare_send_request(mdsc, req, session->s_mds);
2016                 if (!err) {
2017                         ceph_msg_get(req->r_request);
2018                         ceph_con_send(&session->s_con, req->r_request);
2019                 }
2020         }
2021         mutex_unlock(&mdsc->mutex);
2022 }
2023
2024 /*
2025  * Encode information about a cap for a reconnect with the MDS.
2026  */
2027 static int encode_caps_cb(struct inode *inode, struct ceph_cap *cap,
2028                           void *arg)
2029 {
2030         struct ceph_mds_cap_reconnect rec;
2031         struct ceph_inode_info *ci;
2032         struct ceph_pagelist *pagelist = arg;
2033         char *path;
2034         int pathlen, err;
2035         u64 pathbase;
2036         struct dentry *dentry;
2037
2038         ci = cap->ci;
2039
2040         dout(" adding %p ino %llx.%llx cap %p %lld %s\n",
2041              inode, ceph_vinop(inode), cap, cap->cap_id,
2042              ceph_cap_string(cap->issued));
2043         err = ceph_pagelist_encode_64(pagelist, ceph_ino(inode));
2044         if (err)
2045                 return err;
2046
2047         dentry = d_find_alias(inode);
2048         if (dentry) {
2049                 path = ceph_mdsc_build_path(dentry, &pathlen, &pathbase, 0);
2050                 if (IS_ERR(path)) {
2051                         err = PTR_ERR(path);
2052                         BUG_ON(err);
2053                 }
2054         } else {
2055                 path = NULL;
2056                 pathlen = 0;
2057         }
2058         err = ceph_pagelist_encode_string(pagelist, path, pathlen);
2059         if (err)
2060                 goto out;
2061
2062         spin_lock(&inode->i_lock);
2063         cap->seq = 0;        /* reset cap seq */
2064         cap->issue_seq = 0;  /* and issue_seq */
2065         rec.cap_id = cpu_to_le64(cap->cap_id);
2066         rec.pathbase = cpu_to_le64(pathbase);
2067         rec.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2068         rec.issued = cpu_to_le32(cap->issued);
2069         rec.size = cpu_to_le64(inode->i_size);
2070         ceph_encode_timespec(&rec.mtime, &inode->i_mtime);
2071         ceph_encode_timespec(&rec.atime, &inode->i_atime);
2072         rec.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2073         spin_unlock(&inode->i_lock);
2074
2075         err = ceph_pagelist_append(pagelist, &rec, sizeof(rec));
2076
2077 out:
2078         kfree(path);
2079         dput(dentry);
2080         return err;
2081 }
2082
2083
2084 /*
2085  * If an MDS fails and recovers, clients need to reconnect in order to
2086  * reestablish shared state.  This includes all caps issued through
2087  * this session _and_ the snap_realm hierarchy.  Because it's not
2088  * clear which snap realms the mds cares about, we send everything we
2089  * know about.. that ensures we'll then get any new info the
2090  * recovering MDS might have.
2091  *
2092  * This is a relatively heavyweight operation, but it's rare.
2093  *
2094  * called with mdsc->mutex held.
2095  */
2096 static void send_mds_reconnect(struct ceph_mds_client *mdsc, int mds)
2097 {
2098         struct ceph_mds_session *session = NULL;
2099         struct ceph_msg *reply;
2100         int err;
2101         int got;
2102         u64 next_snap_ino = 0;
2103         struct ceph_pagelist *pagelist;
2104
2105         pr_info("reconnect to recovering mds%d\n", mds);
2106
2107         pagelist = kmalloc(sizeof(*pagelist), GFP_NOFS);
2108         if (!pagelist)
2109                 goto fail_nopagelist;
2110         ceph_pagelist_init(pagelist);
2111
2112         reply = ceph_msg_new(CEPH_MSG_CLIENT_RECONNECT, 0, 0, 0, NULL);
2113         if (IS_ERR(reply)) {
2114                 err = PTR_ERR(reply);
2115                 goto fail_nomsg;
2116         }
2117
2118         /* find session */
2119         session = __ceph_lookup_mds_session(mdsc, mds);
2120         mutex_unlock(&mdsc->mutex);    /* drop lock for duration */
2121
2122         if (session) {
2123                 mutex_lock(&session->s_mutex);
2124
2125                 session->s_state = CEPH_MDS_SESSION_RECONNECTING;
2126                 session->s_seq = 0;
2127
2128                 ceph_con_open(&session->s_con,
2129                               ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
2130
2131                 /* replay unsafe requests */
2132                 replay_unsafe_requests(mdsc, session);
2133         } else {
2134                 dout("no session for mds%d, will send short reconnect\n",
2135                      mds);
2136         }
2137
2138         down_read(&mdsc->snap_rwsem);
2139
2140         if (!session)
2141                 goto send;
2142         dout("session %p state %s\n", session,
2143              session_state_name(session->s_state));
2144
2145         /* traverse this session's caps */
2146         err = ceph_pagelist_encode_32(pagelist, session->s_nr_caps);
2147         if (err)
2148                 goto fail;
2149         err = iterate_session_caps(session, encode_caps_cb, pagelist);
2150         if (err < 0)
2151                 goto out;
2152
2153         /*
2154          * snaprealms.  we provide mds with the ino, seq (version), and
2155          * parent for all of our realms.  If the mds has any newer info,
2156          * it will tell us.
2157          */
2158         next_snap_ino = 0;
2159         while (1) {
2160                 struct ceph_snap_realm *realm;
2161                 struct ceph_mds_snaprealm_reconnect sr_rec;
2162                 got = radix_tree_gang_lookup(&mdsc->snap_realms,
2163                                              (void **)&realm, next_snap_ino, 1);
2164                 if (!got)
2165                         break;
2166
2167                 dout(" adding snap realm %llx seq %lld parent %llx\n",
2168                      realm->ino, realm->seq, realm->parent_ino);
2169                 sr_rec.ino = cpu_to_le64(realm->ino);
2170                 sr_rec.seq = cpu_to_le64(realm->seq);
2171                 sr_rec.parent = cpu_to_le64(realm->parent_ino);
2172                 err = ceph_pagelist_append(pagelist, &sr_rec, sizeof(sr_rec));
2173                 if (err)
2174                         goto fail;
2175                 next_snap_ino = realm->ino + 1;
2176         }
2177
2178 send:
2179         reply->pagelist = pagelist;
2180         reply->hdr.data_len = cpu_to_le32(pagelist->length);
2181         reply->nr_pages = calc_pages_for(0, pagelist->length);
2182         ceph_con_send(&session->s_con, reply);
2183
2184         if (session) {
2185                 session->s_state = CEPH_MDS_SESSION_OPEN;
2186                 __wake_requests(mdsc, &session->s_waiting);
2187         }
2188
2189 out:
2190         up_read(&mdsc->snap_rwsem);
2191         if (session) {
2192                 mutex_unlock(&session->s_mutex);
2193                 ceph_put_mds_session(session);
2194         }
2195         mutex_lock(&mdsc->mutex);
2196         return;
2197
2198 fail:
2199         ceph_msg_put(reply);
2200 fail_nomsg:
2201         ceph_pagelist_release(pagelist);
2202         kfree(pagelist);
2203 fail_nopagelist:
2204         pr_err("ENOMEM preparing reconnect for mds%d\n", mds);
2205         goto out;
2206 }
2207
2208
2209 /*
2210  * compare old and new mdsmaps, kicking requests
2211  * and closing out old connections as necessary
2212  *
2213  * called under mdsc->mutex.
2214  */
2215 static void check_new_map(struct ceph_mds_client *mdsc,
2216                           struct ceph_mdsmap *newmap,
2217                           struct ceph_mdsmap *oldmap)
2218 {
2219         int i;
2220         int oldstate, newstate;
2221         struct ceph_mds_session *s;
2222
2223         dout("check_new_map new %u old %u\n",
2224              newmap->m_epoch, oldmap->m_epoch);
2225
2226         for (i = 0; i < oldmap->m_max_mds && i < mdsc->max_sessions; i++) {
2227                 if (mdsc->sessions[i] == NULL)
2228                         continue;
2229                 s = mdsc->sessions[i];
2230                 oldstate = ceph_mdsmap_get_state(oldmap, i);
2231                 newstate = ceph_mdsmap_get_state(newmap, i);
2232
2233                 dout("check_new_map mds%d state %s -> %s (session %s)\n",
2234                      i, ceph_mds_state_name(oldstate),
2235                      ceph_mds_state_name(newstate),
2236                      session_state_name(s->s_state));
2237
2238                 if (memcmp(ceph_mdsmap_get_addr(oldmap, i),
2239                            ceph_mdsmap_get_addr(newmap, i),
2240                            sizeof(struct ceph_entity_addr))) {
2241                         if (s->s_state == CEPH_MDS_SESSION_OPENING) {
2242                                 /* the session never opened, just close it
2243                                  * out now */
2244                                 __wake_requests(mdsc, &s->s_waiting);
2245                                 unregister_session(mdsc, s);
2246                         } else {
2247                                 /* just close it */
2248                                 mutex_unlock(&mdsc->mutex);
2249                                 mutex_lock(&s->s_mutex);
2250                                 mutex_lock(&mdsc->mutex);
2251                                 ceph_con_close(&s->s_con);
2252                                 mutex_unlock(&s->s_mutex);
2253                                 s->s_state = CEPH_MDS_SESSION_RESTARTING;
2254                         }
2255
2256                         /* kick any requests waiting on the recovering mds */
2257                         kick_requests(mdsc, i, 1);
2258                 } else if (oldstate == newstate) {
2259                         continue;  /* nothing new with this mds */
2260                 }
2261
2262                 /*
2263                  * send reconnect?
2264                  */
2265                 if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
2266                     newstate >= CEPH_MDS_STATE_RECONNECT)
2267                         send_mds_reconnect(mdsc, i);
2268
2269                 /*
2270                  * kick requests on any mds that has gone active.
2271                  *
2272                  * kick requests on cur or forwarder: we may have sent
2273                  * the request to mds1, mds1 told us it forwarded it
2274                  * to mds2, but then we learn mds1 failed and can't be
2275                  * sure it successfully forwarded our request before
2276                  * it died.
2277                  */
2278                 if (oldstate < CEPH_MDS_STATE_ACTIVE &&
2279                     newstate >= CEPH_MDS_STATE_ACTIVE) {
2280                         pr_info("mds%d reconnect completed\n", s->s_mds);
2281                         kick_requests(mdsc, i, 1);
2282                         ceph_kick_flushing_caps(mdsc, s);
2283                         wake_up_session_caps(s, 1);
2284                 }
2285         }
2286 }
2287
2288
2289
2290 /*
2291  * leases
2292  */
2293
2294 /*
2295  * caller must hold session s_mutex, dentry->d_lock
2296  */
2297 void __ceph_mdsc_drop_dentry_lease(struct dentry *dentry)
2298 {
2299         struct ceph_dentry_info *di = ceph_dentry(dentry);
2300
2301         ceph_put_mds_session(di->lease_session);
2302         di->lease_session = NULL;
2303 }
2304
2305 static void handle_lease(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
2306 {
2307         struct super_block *sb = mdsc->client->sb;
2308         struct inode *inode;
2309         struct ceph_mds_session *session;
2310         struct ceph_inode_info *ci;
2311         struct dentry *parent, *dentry;
2312         struct ceph_dentry_info *di;
2313         int mds;
2314         struct ceph_mds_lease *h = msg->front.iov_base;
2315         struct ceph_vino vino;
2316         int mask;
2317         struct qstr dname;
2318         int release = 0;
2319
2320         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
2321                 return;
2322         mds = le64_to_cpu(msg->hdr.src.name.num);
2323         dout("handle_lease from mds%d\n", mds);
2324
2325         /* decode */
2326         if (msg->front.iov_len < sizeof(*h) + sizeof(u32))
2327                 goto bad;
2328         vino.ino = le64_to_cpu(h->ino);
2329         vino.snap = CEPH_NOSNAP;
2330         mask = le16_to_cpu(h->mask);
2331         dname.name = (void *)h + sizeof(*h) + sizeof(u32);
2332         dname.len = msg->front.iov_len - sizeof(*h) - sizeof(u32);
2333         if (dname.len != get_unaligned_le32(h+1))
2334                 goto bad;
2335
2336         /* find session */
2337         mutex_lock(&mdsc->mutex);
2338         session = __ceph_lookup_mds_session(mdsc, mds);
2339         mutex_unlock(&mdsc->mutex);
2340         if (!session) {
2341                 pr_err("handle_lease got lease but no session mds%d\n", mds);
2342                 return;
2343         }
2344
2345         mutex_lock(&session->s_mutex);
2346         session->s_seq++;
2347
2348         /* lookup inode */
2349         inode = ceph_find_inode(sb, vino);
2350         dout("handle_lease '%s', mask %d, ino %llx %p\n",
2351              ceph_lease_op_name(h->action), mask, vino.ino, inode);
2352         if (inode == NULL) {
2353                 dout("handle_lease no inode %llx\n", vino.ino);
2354                 goto release;
2355         }
2356         ci = ceph_inode(inode);
2357
2358         /* dentry */
2359         parent = d_find_alias(inode);
2360         if (!parent) {
2361                 dout("no parent dentry on inode %p\n", inode);
2362                 WARN_ON(1);
2363                 goto release;  /* hrm... */
2364         }
2365         dname.hash = full_name_hash(dname.name, dname.len);
2366         dentry = d_lookup(parent, &dname);
2367         dput(parent);
2368         if (!dentry)
2369                 goto release;
2370
2371         spin_lock(&dentry->d_lock);
2372         di = ceph_dentry(dentry);
2373         switch (h->action) {
2374         case CEPH_MDS_LEASE_REVOKE:
2375                 if (di && di->lease_session == session) {
2376                         h->seq = cpu_to_le32(di->lease_seq);
2377                         __ceph_mdsc_drop_dentry_lease(dentry);
2378                 }
2379                 release = 1;
2380                 break;
2381
2382         case CEPH_MDS_LEASE_RENEW:
2383                 if (di && di->lease_session == session &&
2384                     di->lease_gen == session->s_cap_gen &&
2385                     di->lease_renew_from &&
2386                     di->lease_renew_after == 0) {
2387                         unsigned long duration =
2388                                 le32_to_cpu(h->duration_ms) * HZ / 1000;
2389
2390                         di->lease_seq = le32_to_cpu(h->seq);
2391                         dentry->d_time = di->lease_renew_from + duration;
2392                         di->lease_renew_after = di->lease_renew_from +
2393                                 (duration >> 1);
2394                         di->lease_renew_from = 0;
2395                 }
2396                 break;
2397         }
2398         spin_unlock(&dentry->d_lock);
2399         dput(dentry);
2400
2401         if (!release)
2402                 goto out;
2403
2404 release:
2405         /* let's just reuse the same message */
2406         h->action = CEPH_MDS_LEASE_REVOKE_ACK;
2407         ceph_msg_get(msg);
2408         ceph_con_send(&session->s_con, msg);
2409
2410 out:
2411         iput(inode);
2412         mutex_unlock(&session->s_mutex);
2413         ceph_put_mds_session(session);
2414         return;
2415
2416 bad:
2417         pr_err("corrupt lease message\n");
2418         ceph_msg_dump(msg);
2419 }
2420
2421 void ceph_mdsc_lease_send_msg(struct ceph_mds_session *session,
2422                               struct inode *inode,
2423                               struct dentry *dentry, char action,
2424                               u32 seq)
2425 {
2426         struct ceph_msg *msg;
2427         struct ceph_mds_lease *lease;
2428         int len = sizeof(*lease) + sizeof(u32);
2429         int dnamelen = 0;
2430
2431         dout("lease_send_msg inode %p dentry %p %s to mds%d\n",
2432              inode, dentry, ceph_lease_op_name(action), session->s_mds);
2433         dnamelen = dentry->d_name.len;
2434         len += dnamelen;
2435
2436         msg = ceph_msg_new(CEPH_MSG_CLIENT_LEASE, len, 0, 0, NULL);
2437         if (IS_ERR(msg))
2438                 return;
2439         lease = msg->front.iov_base;
2440         lease->action = action;
2441         lease->mask = cpu_to_le16(CEPH_LOCK_DN);
2442         lease->ino = cpu_to_le64(ceph_vino(inode).ino);
2443         lease->first = lease->last = cpu_to_le64(ceph_vino(inode).snap);
2444         lease->seq = cpu_to_le32(seq);
2445         put_unaligned_le32(dnamelen, lease + 1);
2446         memcpy((void *)(lease + 1) + 4, dentry->d_name.name, dnamelen);
2447
2448         /*
2449          * if this is a preemptive lease RELEASE, no need to
2450          * flush request stream, since the actual request will
2451          * soon follow.
2452          */
2453         msg->more_to_follow = (action == CEPH_MDS_LEASE_RELEASE);
2454
2455         ceph_con_send(&session->s_con, msg);
2456 }
2457
2458 /*
2459  * Preemptively release a lease we expect to invalidate anyway.
2460  * Pass @inode always, @dentry is optional.
2461  */
2462 void ceph_mdsc_lease_release(struct ceph_mds_client *mdsc, struct inode *inode,
2463                              struct dentry *dentry, int mask)
2464 {
2465         struct ceph_dentry_info *di;
2466         struct ceph_mds_session *session;
2467         u32 seq;
2468
2469         BUG_ON(inode == NULL);
2470         BUG_ON(dentry == NULL);
2471         BUG_ON(mask != CEPH_LOCK_DN);
2472
2473         /* is dentry lease valid? */
2474         spin_lock(&dentry->d_lock);
2475         di = ceph_dentry(dentry);
2476         if (!di || !di->lease_session ||
2477             di->lease_session->s_mds < 0 ||
2478             di->lease_gen != di->lease_session->s_cap_gen ||
2479             !time_before(jiffies, dentry->d_time)) {
2480                 dout("lease_release inode %p dentry %p -- "
2481                      "no lease on %d\n",
2482                      inode, dentry, mask);
2483                 spin_unlock(&dentry->d_lock);
2484                 return;
2485         }
2486
2487         /* we do have a lease on this dentry; note mds and seq */
2488         session = ceph_get_mds_session(di->lease_session);
2489         seq = di->lease_seq;
2490         __ceph_mdsc_drop_dentry_lease(dentry);
2491         spin_unlock(&dentry->d_lock);
2492
2493         dout("lease_release inode %p dentry %p mask %d to mds%d\n",
2494              inode, dentry, mask, session->s_mds);
2495         ceph_mdsc_lease_send_msg(session, inode, dentry,
2496                                  CEPH_MDS_LEASE_RELEASE, seq);
2497         ceph_put_mds_session(session);
2498 }
2499
2500 /*
2501  * drop all leases (and dentry refs) in preparation for umount
2502  */
2503 static void drop_leases(struct ceph_mds_client *mdsc)
2504 {
2505         int i;
2506
2507         dout("drop_leases\n");
2508         mutex_lock(&mdsc->mutex);
2509         for (i = 0; i < mdsc->max_sessions; i++) {
2510                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2511                 if (!s)
2512                         continue;
2513                 mutex_unlock(&mdsc->mutex);
2514                 mutex_lock(&s->s_mutex);
2515                 mutex_unlock(&s->s_mutex);
2516                 ceph_put_mds_session(s);
2517                 mutex_lock(&mdsc->mutex);
2518         }
2519         mutex_unlock(&mdsc->mutex);
2520 }
2521
2522
2523
2524 /*
2525  * delayed work -- periodically trim expired leases, renew caps with mds
2526  */
2527 static void schedule_delayed(struct ceph_mds_client *mdsc)
2528 {
2529         int delay = 5;
2530         unsigned hz = round_jiffies_relative(HZ * delay);
2531         schedule_delayed_work(&mdsc->delayed_work, hz);
2532 }
2533
2534 static void delayed_work(struct work_struct *work)
2535 {
2536         int i;
2537         struct ceph_mds_client *mdsc =
2538                 container_of(work, struct ceph_mds_client, delayed_work.work);
2539         int renew_interval;
2540         int renew_caps;
2541
2542         dout("mdsc delayed_work\n");
2543         ceph_check_delayed_caps(mdsc);
2544
2545         mutex_lock(&mdsc->mutex);
2546         renew_interval = mdsc->mdsmap->m_session_timeout >> 2;
2547         renew_caps = time_after_eq(jiffies, HZ*renew_interval +
2548                                    mdsc->last_renew_caps);
2549         if (renew_caps)
2550                 mdsc->last_renew_caps = jiffies;
2551
2552         for (i = 0; i < mdsc->max_sessions; i++) {
2553                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2554                 if (s == NULL)
2555                         continue;
2556                 if (s->s_state == CEPH_MDS_SESSION_CLOSING) {
2557                         dout("resending session close request for mds%d\n",
2558                              s->s_mds);
2559                         request_close_session(mdsc, s);
2560                         ceph_put_mds_session(s);
2561                         continue;
2562                 }
2563                 if (s->s_ttl && time_after(jiffies, s->s_ttl)) {
2564                         if (s->s_state == CEPH_MDS_SESSION_OPEN) {
2565                                 s->s_state = CEPH_MDS_SESSION_HUNG;
2566                                 pr_info("mds%d hung\n", s->s_mds);
2567                         }
2568                 }
2569                 if (s->s_state < CEPH_MDS_SESSION_OPEN) {
2570                         /* this mds is failed or recovering, just wait */
2571                         ceph_put_mds_session(s);
2572                         continue;
2573                 }
2574                 mutex_unlock(&mdsc->mutex);
2575
2576                 mutex_lock(&s->s_mutex);
2577                 if (renew_caps)
2578                         send_renew_caps(mdsc, s);
2579                 else
2580                         ceph_con_keepalive(&s->s_con);
2581                 add_cap_releases(mdsc, s, -1);
2582                 send_cap_releases(mdsc, s);
2583                 mutex_unlock(&s->s_mutex);
2584                 ceph_put_mds_session(s);
2585
2586                 mutex_lock(&mdsc->mutex);
2587         }
2588         mutex_unlock(&mdsc->mutex);
2589
2590         schedule_delayed(mdsc);
2591 }
2592
2593
2594 int ceph_mdsc_init(struct ceph_mds_client *mdsc, struct ceph_client *client)
2595 {
2596         mdsc->client = client;
2597         mutex_init(&mdsc->mutex);
2598         mdsc->mdsmap = kzalloc(sizeof(*mdsc->mdsmap), GFP_NOFS);
2599         init_completion(&mdsc->safe_umount_waiters);
2600         init_completion(&mdsc->session_close_waiters);
2601         INIT_LIST_HEAD(&mdsc->waiting_for_map);
2602         mdsc->sessions = NULL;
2603         mdsc->max_sessions = 0;
2604         mdsc->stopping = 0;
2605         init_rwsem(&mdsc->snap_rwsem);
2606         INIT_RADIX_TREE(&mdsc->snap_realms, GFP_NOFS);
2607         INIT_LIST_HEAD(&mdsc->snap_empty);
2608         spin_lock_init(&mdsc->snap_empty_lock);
2609         mdsc->last_tid = 0;
2610         mdsc->request_tree = RB_ROOT;
2611         INIT_DELAYED_WORK(&mdsc->delayed_work, delayed_work);
2612         mdsc->last_renew_caps = jiffies;
2613         INIT_LIST_HEAD(&mdsc->cap_delay_list);
2614         spin_lock_init(&mdsc->cap_delay_lock);
2615         INIT_LIST_HEAD(&mdsc->snap_flush_list);
2616         spin_lock_init(&mdsc->snap_flush_lock);
2617         mdsc->cap_flush_seq = 0;
2618         INIT_LIST_HEAD(&mdsc->cap_dirty);
2619         mdsc->num_cap_flushing = 0;
2620         spin_lock_init(&mdsc->cap_dirty_lock);
2621         init_waitqueue_head(&mdsc->cap_flushing_wq);
2622         spin_lock_init(&mdsc->dentry_lru_lock);
2623         INIT_LIST_HEAD(&mdsc->dentry_lru);
2624         return 0;
2625 }
2626
2627 /*
2628  * Wait for safe replies on open mds requests.  If we time out, drop
2629  * all requests from the tree to avoid dangling dentry refs.
2630  */
2631 static void wait_requests(struct ceph_mds_client *mdsc)
2632 {
2633         struct ceph_mds_request *req;
2634         struct ceph_client *client = mdsc->client;
2635
2636         mutex_lock(&mdsc->mutex);
2637         if (__get_oldest_req(mdsc)) {
2638                 mutex_unlock(&mdsc->mutex);
2639
2640                 dout("wait_requests waiting for requests\n");
2641                 wait_for_completion_timeout(&mdsc->safe_umount_waiters,
2642                                     client->mount_args->mount_timeout * HZ);
2643
2644                 /* tear down remaining requests */
2645                 mutex_lock(&mdsc->mutex);
2646                 while ((req = __get_oldest_req(mdsc))) {
2647                         dout("wait_requests timed out on tid %llu\n",
2648                              req->r_tid);
2649                         __unregister_request(mdsc, req);
2650                 }
2651         }
2652         mutex_unlock(&mdsc->mutex);
2653         dout("wait_requests done\n");
2654 }
2655
2656 /*
2657  * called before mount is ro, and before dentries are torn down.
2658  * (hmm, does this still race with new lookups?)
2659  */
2660 void ceph_mdsc_pre_umount(struct ceph_mds_client *mdsc)
2661 {
2662         dout("pre_umount\n");
2663         mdsc->stopping = 1;
2664
2665         drop_leases(mdsc);
2666         ceph_flush_dirty_caps(mdsc);
2667         wait_requests(mdsc);
2668 }
2669
2670 /*
2671  * wait for all write mds requests to flush.
2672  */
2673 static void wait_unsafe_requests(struct ceph_mds_client *mdsc, u64 want_tid)
2674 {
2675         struct ceph_mds_request *req = NULL;
2676         struct rb_node *n;
2677
2678         mutex_lock(&mdsc->mutex);
2679         dout("wait_unsafe_requests want %lld\n", want_tid);
2680         req = __get_oldest_req(mdsc);
2681         while (req && req->r_tid <= want_tid) {
2682                 if ((req->r_op & CEPH_MDS_OP_WRITE)) {
2683                         /* write op */
2684                         ceph_mdsc_get_request(req);
2685                         mutex_unlock(&mdsc->mutex);
2686                         dout("wait_unsafe_requests  wait on %llu (want %llu)\n",
2687                              req->r_tid, want_tid);
2688                         wait_for_completion(&req->r_safe_completion);
2689                         mutex_lock(&mdsc->mutex);
2690                         n = rb_next(&req->r_node);
2691                         ceph_mdsc_put_request(req);
2692                 } else {
2693                         n = rb_next(&req->r_node);
2694                 }
2695                 if (!n)
2696                         break;
2697                 req = rb_entry(n, struct ceph_mds_request, r_node);
2698         }
2699         mutex_unlock(&mdsc->mutex);
2700         dout("wait_unsafe_requests done\n");
2701 }
2702
2703 void ceph_mdsc_sync(struct ceph_mds_client *mdsc)
2704 {
2705         u64 want_tid, want_flush;
2706
2707         dout("sync\n");
2708         mutex_lock(&mdsc->mutex);
2709         want_tid = mdsc->last_tid;
2710         want_flush = mdsc->cap_flush_seq;
2711         mutex_unlock(&mdsc->mutex);
2712         dout("sync want tid %lld flush_seq %lld\n", want_tid, want_flush);
2713
2714         ceph_flush_dirty_caps(mdsc);
2715
2716         wait_unsafe_requests(mdsc, want_tid);
2717         wait_event(mdsc->cap_flushing_wq, check_cap_flush(mdsc, want_flush));
2718 }
2719
2720
2721 /*
2722  * called after sb is ro.
2723  */
2724 void ceph_mdsc_close_sessions(struct ceph_mds_client *mdsc)
2725 {
2726         struct ceph_mds_session *session;
2727         int i;
2728         int n;
2729         struct ceph_client *client = mdsc->client;
2730         unsigned long started, timeout = client->mount_args->mount_timeout * HZ;
2731
2732         dout("close_sessions\n");
2733
2734         mutex_lock(&mdsc->mutex);
2735
2736         /* close sessions */
2737         started = jiffies;
2738         while (time_before(jiffies, started + timeout)) {
2739                 dout("closing sessions\n");
2740                 n = 0;
2741                 for (i = 0; i < mdsc->max_sessions; i++) {
2742                         session = __ceph_lookup_mds_session(mdsc, i);
2743                         if (!session)
2744                                 continue;
2745                         mutex_unlock(&mdsc->mutex);
2746                         mutex_lock(&session->s_mutex);
2747                         __close_session(mdsc, session);
2748                         mutex_unlock(&session->s_mutex);
2749                         ceph_put_mds_session(session);
2750                         mutex_lock(&mdsc->mutex);
2751                         n++;
2752                 }
2753                 if (n == 0)
2754                         break;
2755
2756                 if (client->mount_state == CEPH_MOUNT_SHUTDOWN)
2757                         break;
2758
2759                 dout("waiting for sessions to close\n");
2760                 mutex_unlock(&mdsc->mutex);
2761                 wait_for_completion_timeout(&mdsc->session_close_waiters,
2762                                             timeout);
2763                 mutex_lock(&mdsc->mutex);
2764         }
2765
2766         /* tear down remaining sessions */
2767         for (i = 0; i < mdsc->max_sessions; i++) {
2768                 if (mdsc->sessions[i]) {
2769                         session = get_session(mdsc->sessions[i]);
2770                         unregister_session(mdsc, session);
2771                         mutex_unlock(&mdsc->mutex);
2772                         mutex_lock(&session->s_mutex);
2773                         remove_session_caps(session);
2774                         mutex_unlock(&session->s_mutex);
2775                         ceph_put_mds_session(session);
2776                         mutex_lock(&mdsc->mutex);
2777                 }
2778         }
2779
2780         WARN_ON(!list_empty(&mdsc->cap_delay_list));
2781
2782         mutex_unlock(&mdsc->mutex);
2783
2784         ceph_cleanup_empty_realms(mdsc);
2785
2786         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
2787
2788         dout("stopped\n");
2789 }
2790
2791 void ceph_mdsc_stop(struct ceph_mds_client *mdsc)
2792 {
2793         dout("stop\n");
2794         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
2795         if (mdsc->mdsmap)
2796                 ceph_mdsmap_destroy(mdsc->mdsmap);
2797         kfree(mdsc->sessions);
2798 }
2799
2800
2801 /*
2802  * handle mds map update.
2803  */
2804 void ceph_mdsc_handle_map(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
2805 {
2806         u32 epoch;
2807         u32 maplen;
2808         void *p = msg->front.iov_base;
2809         void *end = p + msg->front.iov_len;
2810         struct ceph_mdsmap *newmap, *oldmap;
2811         struct ceph_fsid fsid;
2812         int err = -EINVAL;
2813
2814         ceph_decode_need(&p, end, sizeof(fsid)+2*sizeof(u32), bad);
2815         ceph_decode_copy(&p, &fsid, sizeof(fsid));
2816         if (ceph_check_fsid(mdsc->client, &fsid) < 0)
2817                 return;
2818         epoch = ceph_decode_32(&p);
2819         maplen = ceph_decode_32(&p);
2820         dout("handle_map epoch %u len %d\n", epoch, (int)maplen);
2821
2822         /* do we need it? */
2823         ceph_monc_got_mdsmap(&mdsc->client->monc, epoch);
2824         mutex_lock(&mdsc->mutex);
2825         if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) {
2826                 dout("handle_map epoch %u <= our %u\n",
2827                      epoch, mdsc->mdsmap->m_epoch);
2828                 mutex_unlock(&mdsc->mutex);
2829                 return;
2830         }
2831
2832         newmap = ceph_mdsmap_decode(&p, end);
2833         if (IS_ERR(newmap)) {
2834                 err = PTR_ERR(newmap);
2835                 goto bad_unlock;
2836         }
2837
2838         /* swap into place */
2839         if (mdsc->mdsmap) {
2840                 oldmap = mdsc->mdsmap;
2841                 mdsc->mdsmap = newmap;
2842                 check_new_map(mdsc, newmap, oldmap);
2843                 ceph_mdsmap_destroy(oldmap);
2844         } else {
2845                 mdsc->mdsmap = newmap;  /* first mds map */
2846         }
2847         mdsc->client->sb->s_maxbytes = mdsc->mdsmap->m_max_file_size;
2848
2849         __wake_requests(mdsc, &mdsc->waiting_for_map);
2850
2851         mutex_unlock(&mdsc->mutex);
2852         schedule_delayed(mdsc);
2853         return;
2854
2855 bad_unlock:
2856         mutex_unlock(&mdsc->mutex);
2857 bad:
2858         pr_err("error decoding mdsmap %d\n", err);
2859         return;
2860 }
2861
2862 static struct ceph_connection *con_get(struct ceph_connection *con)
2863 {
2864         struct ceph_mds_session *s = con->private;
2865
2866         if (get_session(s)) {
2867                 dout("mdsc con_get %p %d -> %d\n", s,
2868                      atomic_read(&s->s_ref) - 1, atomic_read(&s->s_ref));
2869                 return con;
2870         }
2871         dout("mdsc con_get %p FAIL\n", s);
2872         return NULL;
2873 }
2874
2875 static void con_put(struct ceph_connection *con)
2876 {
2877         struct ceph_mds_session *s = con->private;
2878
2879         dout("mdsc con_put %p %d -> %d\n", s, atomic_read(&s->s_ref),
2880              atomic_read(&s->s_ref) - 1);
2881         ceph_put_mds_session(s);
2882 }
2883
2884 /*
2885  * if the client is unresponsive for long enough, the mds will kill
2886  * the session entirely.
2887  */
2888 static void peer_reset(struct ceph_connection *con)
2889 {
2890         struct ceph_mds_session *s = con->private;
2891
2892         pr_err("mds%d gave us the boot.  IMPLEMENT RECONNECT.\n",
2893                s->s_mds);
2894 }
2895
2896 static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
2897 {
2898         struct ceph_mds_session *s = con->private;
2899         struct ceph_mds_client *mdsc = s->s_mdsc;
2900         int type = le16_to_cpu(msg->hdr.type);
2901
2902         switch (type) {
2903         case CEPH_MSG_MDS_MAP:
2904                 ceph_mdsc_handle_map(mdsc, msg);
2905                 break;
2906         case CEPH_MSG_CLIENT_SESSION:
2907                 handle_session(s, msg);
2908                 break;
2909         case CEPH_MSG_CLIENT_REPLY:
2910                 handle_reply(s, msg);
2911                 break;
2912         case CEPH_MSG_CLIENT_REQUEST_FORWARD:
2913                 handle_forward(mdsc, msg);
2914                 break;
2915         case CEPH_MSG_CLIENT_CAPS:
2916                 ceph_handle_caps(s, msg);
2917                 break;
2918         case CEPH_MSG_CLIENT_SNAP:
2919                 ceph_handle_snap(mdsc, msg);
2920                 break;
2921         case CEPH_MSG_CLIENT_LEASE:
2922                 handle_lease(mdsc, msg);
2923                 break;
2924
2925         default:
2926                 pr_err("received unknown message type %d %s\n", type,
2927                        ceph_msg_type_name(type));
2928         }
2929         ceph_msg_put(msg);
2930 }
2931
2932 /*
2933  * authentication
2934  */
2935 static int get_authorizer(struct ceph_connection *con,
2936                           void **buf, int *len, int *proto,
2937                           void **reply_buf, int *reply_len, int force_new)
2938 {
2939         struct ceph_mds_session *s = con->private;
2940         struct ceph_mds_client *mdsc = s->s_mdsc;
2941         struct ceph_auth_client *ac = mdsc->client->monc.auth;
2942         int ret = 0;
2943
2944         if (force_new && s->s_authorizer) {
2945                 ac->ops->destroy_authorizer(ac, s->s_authorizer);
2946                 s->s_authorizer = NULL;
2947         }
2948         if (s->s_authorizer == NULL) {
2949                 if (ac->ops->create_authorizer) {
2950                         ret = ac->ops->create_authorizer(
2951                                 ac, CEPH_ENTITY_TYPE_MDS,
2952                                 &s->s_authorizer,
2953                                 &s->s_authorizer_buf,
2954                                 &s->s_authorizer_buf_len,
2955                                 &s->s_authorizer_reply_buf,
2956                                 &s->s_authorizer_reply_buf_len);
2957                         if (ret)
2958                                 return ret;
2959                 }
2960         }
2961
2962         *proto = ac->protocol;
2963         *buf = s->s_authorizer_buf;
2964         *len = s->s_authorizer_buf_len;
2965         *reply_buf = s->s_authorizer_reply_buf;
2966         *reply_len = s->s_authorizer_reply_buf_len;
2967         return 0;
2968 }
2969
2970
2971 static int verify_authorizer_reply(struct ceph_connection *con, int len)
2972 {
2973         struct ceph_mds_session *s = con->private;
2974         struct ceph_mds_client *mdsc = s->s_mdsc;
2975         struct ceph_auth_client *ac = mdsc->client->monc.auth;
2976
2977         return ac->ops->verify_authorizer_reply(ac, s->s_authorizer, len);
2978 }
2979
2980 static int invalidate_authorizer(struct ceph_connection *con)
2981 {
2982         struct ceph_mds_session *s = con->private;
2983         struct ceph_mds_client *mdsc = s->s_mdsc;
2984         struct ceph_auth_client *ac = mdsc->client->monc.auth;
2985
2986         if (ac->ops->invalidate_authorizer)
2987                 ac->ops->invalidate_authorizer(ac, CEPH_ENTITY_TYPE_MDS);
2988
2989         return ceph_monc_validate_auth(&mdsc->client->monc);
2990 }
2991
2992 const static struct ceph_connection_operations mds_con_ops = {
2993         .get = con_get,
2994         .put = con_put,
2995         .dispatch = dispatch,
2996         .get_authorizer = get_authorizer,
2997         .verify_authorizer_reply = verify_authorizer_reply,
2998         .invalidate_authorizer = invalidate_authorizer,
2999         .peer_reset = peer_reset,
3000 };
3001
3002
3003
3004
3005 /* eof */