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