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