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