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