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