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