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