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