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