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