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