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