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