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