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