xref: /openbmc/linux/fs/ceph/snap.c (revision e4c881d2)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/fs.h>
5 #include <linux/sort.h>
6 #include <linux/slab.h>
7 #include <linux/iversion.h>
8 #include "super.h"
9 #include "mds_client.h"
10 #include <linux/ceph/decode.h>
11 
12 /* unused map expires after 5 minutes */
13 #define CEPH_SNAPID_MAP_TIMEOUT	(5 * 60 * HZ)
14 
15 /*
16  * Snapshots in ceph are driven in large part by cooperation from the
17  * client.  In contrast to local file systems or file servers that
18  * implement snapshots at a single point in the system, ceph's
19  * distributed access to storage requires clients to help decide
20  * whether a write logically occurs before or after a recently created
21  * snapshot.
22  *
23  * This provides a perfect instantanous client-wide snapshot.  Between
24  * clients, however, snapshots may appear to be applied at slightly
25  * different points in time, depending on delays in delivering the
26  * snapshot notification.
27  *
28  * Snapshots are _not_ file system-wide.  Instead, each snapshot
29  * applies to the subdirectory nested beneath some directory.  This
30  * effectively divides the hierarchy into multiple "realms," where all
31  * of the files contained by each realm share the same set of
32  * snapshots.  An individual realm's snap set contains snapshots
33  * explicitly created on that realm, as well as any snaps in its
34  * parent's snap set _after_ the point at which the parent became it's
35  * parent (due to, say, a rename).  Similarly, snaps from prior parents
36  * during the time intervals during which they were the parent are included.
37  *
38  * The client is spared most of this detail, fortunately... it must only
39  * maintains a hierarchy of realms reflecting the current parent/child
40  * realm relationship, and for each realm has an explicit list of snaps
41  * inherited from prior parents.
42  *
43  * A snap_realm struct is maintained for realms containing every inode
44  * with an open cap in the system.  (The needed snap realm information is
45  * provided by the MDS whenever a cap is issued, i.e., on open.)  A 'seq'
46  * version number is used to ensure that as realm parameters change (new
47  * snapshot, new parent, etc.) the client's realm hierarchy is updated.
48  *
49  * The realm hierarchy drives the generation of a 'snap context' for each
50  * realm, which simply lists the resulting set of snaps for the realm.  This
51  * is attached to any writes sent to OSDs.
52  */
53 /*
54  * Unfortunately error handling is a bit mixed here.  If we get a snap
55  * update, but don't have enough memory to update our realm hierarchy,
56  * it's not clear what we can do about it (besides complaining to the
57  * console).
58  */
59 
60 
61 /*
62  * increase ref count for the realm
63  *
64  * caller must hold snap_rwsem.
65  */
66 void ceph_get_snap_realm(struct ceph_mds_client *mdsc,
67 			 struct ceph_snap_realm *realm)
68 {
69 	lockdep_assert_held(&mdsc->snap_rwsem);
70 
71 	/*
72 	 * The 0->1 and 1->0 transitions must take the snap_empty_lock
73 	 * atomically with the refcount change. Go ahead and bump the
74 	 * nref here, unless it's 0, in which case we take the spinlock
75 	 * and then do the increment and remove it from the list.
76 	 */
77 	if (atomic_inc_not_zero(&realm->nref))
78 		return;
79 
80 	spin_lock(&mdsc->snap_empty_lock);
81 	if (atomic_inc_return(&realm->nref) == 1)
82 		list_del_init(&realm->empty_item);
83 	spin_unlock(&mdsc->snap_empty_lock);
84 }
85 
86 static void __insert_snap_realm(struct rb_root *root,
87 				struct ceph_snap_realm *new)
88 {
89 	struct rb_node **p = &root->rb_node;
90 	struct rb_node *parent = NULL;
91 	struct ceph_snap_realm *r = NULL;
92 
93 	while (*p) {
94 		parent = *p;
95 		r = rb_entry(parent, struct ceph_snap_realm, node);
96 		if (new->ino < r->ino)
97 			p = &(*p)->rb_left;
98 		else if (new->ino > r->ino)
99 			p = &(*p)->rb_right;
100 		else
101 			BUG();
102 	}
103 
104 	rb_link_node(&new->node, parent, p);
105 	rb_insert_color(&new->node, root);
106 }
107 
108 /*
109  * create and get the realm rooted at @ino and bump its ref count.
110  *
111  * caller must hold snap_rwsem for write.
112  */
113 static struct ceph_snap_realm *ceph_create_snap_realm(
114 	struct ceph_mds_client *mdsc,
115 	u64 ino)
116 {
117 	struct ceph_snap_realm *realm;
118 
119 	lockdep_assert_held_write(&mdsc->snap_rwsem);
120 
121 	realm = kzalloc(sizeof(*realm), GFP_NOFS);
122 	if (!realm)
123 		return ERR_PTR(-ENOMEM);
124 
125 	/* Do not release the global dummy snaprealm until unmouting */
126 	if (ino == CEPH_INO_GLOBAL_SNAPREALM)
127 		atomic_set(&realm->nref, 2);
128 	else
129 		atomic_set(&realm->nref, 1);
130 	realm->ino = ino;
131 	INIT_LIST_HEAD(&realm->children);
132 	INIT_LIST_HEAD(&realm->child_item);
133 	INIT_LIST_HEAD(&realm->empty_item);
134 	INIT_LIST_HEAD(&realm->dirty_item);
135 	INIT_LIST_HEAD(&realm->rebuild_item);
136 	INIT_LIST_HEAD(&realm->inodes_with_caps);
137 	spin_lock_init(&realm->inodes_with_caps_lock);
138 	__insert_snap_realm(&mdsc->snap_realms, realm);
139 	mdsc->num_snap_realms++;
140 
141 	dout("%s %llx %p\n", __func__, realm->ino, realm);
142 	return realm;
143 }
144 
145 /*
146  * lookup the realm rooted at @ino.
147  *
148  * caller must hold snap_rwsem.
149  */
150 static struct ceph_snap_realm *__lookup_snap_realm(struct ceph_mds_client *mdsc,
151 						   u64 ino)
152 {
153 	struct rb_node *n = mdsc->snap_realms.rb_node;
154 	struct ceph_snap_realm *r;
155 
156 	lockdep_assert_held(&mdsc->snap_rwsem);
157 
158 	while (n) {
159 		r = rb_entry(n, struct ceph_snap_realm, node);
160 		if (ino < r->ino)
161 			n = n->rb_left;
162 		else if (ino > r->ino)
163 			n = n->rb_right;
164 		else {
165 			dout("%s %llx %p\n", __func__, r->ino, r);
166 			return r;
167 		}
168 	}
169 	return NULL;
170 }
171 
172 struct ceph_snap_realm *ceph_lookup_snap_realm(struct ceph_mds_client *mdsc,
173 					       u64 ino)
174 {
175 	struct ceph_snap_realm *r;
176 	r = __lookup_snap_realm(mdsc, ino);
177 	if (r)
178 		ceph_get_snap_realm(mdsc, r);
179 	return r;
180 }
181 
182 static void __put_snap_realm(struct ceph_mds_client *mdsc,
183 			     struct ceph_snap_realm *realm);
184 
185 /*
186  * called with snap_rwsem (write)
187  */
188 static void __destroy_snap_realm(struct ceph_mds_client *mdsc,
189 				 struct ceph_snap_realm *realm)
190 {
191 	lockdep_assert_held_write(&mdsc->snap_rwsem);
192 
193 	dout("%s %p %llx\n", __func__, realm, realm->ino);
194 
195 	rb_erase(&realm->node, &mdsc->snap_realms);
196 	mdsc->num_snap_realms--;
197 
198 	if (realm->parent) {
199 		list_del_init(&realm->child_item);
200 		__put_snap_realm(mdsc, realm->parent);
201 	}
202 
203 	kfree(realm->prior_parent_snaps);
204 	kfree(realm->snaps);
205 	ceph_put_snap_context(realm->cached_context);
206 	kfree(realm);
207 }
208 
209 /*
210  * caller holds snap_rwsem (write)
211  */
212 static void __put_snap_realm(struct ceph_mds_client *mdsc,
213 			     struct ceph_snap_realm *realm)
214 {
215 	lockdep_assert_held_write(&mdsc->snap_rwsem);
216 
217 	/*
218 	 * We do not require the snap_empty_lock here, as any caller that
219 	 * increments the value must hold the snap_rwsem.
220 	 */
221 	if (atomic_dec_and_test(&realm->nref))
222 		__destroy_snap_realm(mdsc, realm);
223 }
224 
225 /*
226  * See comments in ceph_get_snap_realm. Caller needn't hold any locks.
227  */
228 void ceph_put_snap_realm(struct ceph_mds_client *mdsc,
229 			 struct ceph_snap_realm *realm)
230 {
231 	if (!atomic_dec_and_lock(&realm->nref, &mdsc->snap_empty_lock))
232 		return;
233 
234 	if (down_write_trylock(&mdsc->snap_rwsem)) {
235 		spin_unlock(&mdsc->snap_empty_lock);
236 		__destroy_snap_realm(mdsc, realm);
237 		up_write(&mdsc->snap_rwsem);
238 	} else {
239 		list_add(&realm->empty_item, &mdsc->snap_empty);
240 		spin_unlock(&mdsc->snap_empty_lock);
241 	}
242 }
243 
244 /*
245  * Clean up any realms whose ref counts have dropped to zero.  Note
246  * that this does not include realms who were created but not yet
247  * used.
248  *
249  * Called under snap_rwsem (write)
250  */
251 static void __cleanup_empty_realms(struct ceph_mds_client *mdsc)
252 {
253 	struct ceph_snap_realm *realm;
254 
255 	lockdep_assert_held_write(&mdsc->snap_rwsem);
256 
257 	spin_lock(&mdsc->snap_empty_lock);
258 	while (!list_empty(&mdsc->snap_empty)) {
259 		realm = list_first_entry(&mdsc->snap_empty,
260 				   struct ceph_snap_realm, empty_item);
261 		list_del(&realm->empty_item);
262 		spin_unlock(&mdsc->snap_empty_lock);
263 		__destroy_snap_realm(mdsc, realm);
264 		spin_lock(&mdsc->snap_empty_lock);
265 	}
266 	spin_unlock(&mdsc->snap_empty_lock);
267 }
268 
269 void ceph_cleanup_global_and_empty_realms(struct ceph_mds_client *mdsc)
270 {
271 	struct ceph_snap_realm *global_realm;
272 
273 	down_write(&mdsc->snap_rwsem);
274 	global_realm = __lookup_snap_realm(mdsc, CEPH_INO_GLOBAL_SNAPREALM);
275 	if (global_realm)
276 		ceph_put_snap_realm(mdsc, global_realm);
277 	__cleanup_empty_realms(mdsc);
278 	up_write(&mdsc->snap_rwsem);
279 }
280 
281 /*
282  * adjust the parent realm of a given @realm.  adjust child list, and parent
283  * pointers, and ref counts appropriately.
284  *
285  * return true if parent was changed, 0 if unchanged, <0 on error.
286  *
287  * caller must hold snap_rwsem for write.
288  */
289 static int adjust_snap_realm_parent(struct ceph_mds_client *mdsc,
290 				    struct ceph_snap_realm *realm,
291 				    u64 parentino)
292 {
293 	struct ceph_snap_realm *parent;
294 
295 	lockdep_assert_held_write(&mdsc->snap_rwsem);
296 
297 	if (realm->parent_ino == parentino)
298 		return 0;
299 
300 	parent = ceph_lookup_snap_realm(mdsc, parentino);
301 	if (!parent) {
302 		parent = ceph_create_snap_realm(mdsc, parentino);
303 		if (IS_ERR(parent))
304 			return PTR_ERR(parent);
305 	}
306 	dout("%s %llx %p: %llx %p -> %llx %p\n", __func__, realm->ino,
307 	     realm, realm->parent_ino, realm->parent, parentino, parent);
308 	if (realm->parent) {
309 		list_del_init(&realm->child_item);
310 		ceph_put_snap_realm(mdsc, realm->parent);
311 	}
312 	realm->parent_ino = parentino;
313 	realm->parent = parent;
314 	list_add(&realm->child_item, &parent->children);
315 	return 1;
316 }
317 
318 
319 static int cmpu64_rev(const void *a, const void *b)
320 {
321 	if (*(u64 *)a < *(u64 *)b)
322 		return 1;
323 	if (*(u64 *)a > *(u64 *)b)
324 		return -1;
325 	return 0;
326 }
327 
328 
329 /*
330  * build the snap context for a given realm.
331  */
332 static int build_snap_context(struct ceph_mds_client *mdsc,
333 			      struct ceph_snap_realm *realm,
334 			      struct list_head *realm_queue,
335 			      struct list_head *dirty_realms)
336 {
337 	struct ceph_snap_realm *parent = realm->parent;
338 	struct ceph_snap_context *snapc;
339 	int err = 0;
340 	u32 num = realm->num_prior_parent_snaps + realm->num_snaps;
341 
342 	/*
343 	 * build parent context, if it hasn't been built.
344 	 * conservatively estimate that all parent snaps might be
345 	 * included by us.
346 	 */
347 	if (parent) {
348 		if (!parent->cached_context) {
349 			/* add to the queue head */
350 			list_add(&parent->rebuild_item, realm_queue);
351 			return 1;
352 		}
353 		num += parent->cached_context->num_snaps;
354 	}
355 
356 	/* do i actually need to update?  not if my context seq
357 	   matches realm seq, and my parents' does to.  (this works
358 	   because we rebuild_snap_realms() works _downward_ in
359 	   hierarchy after each update.) */
360 	if (realm->cached_context &&
361 	    realm->cached_context->seq == realm->seq &&
362 	    (!parent ||
363 	     realm->cached_context->seq >= parent->cached_context->seq)) {
364 		dout("%s %llx %p: %p seq %lld (%u snaps) (unchanged)\n",
365 		     __func__, realm->ino, realm, realm->cached_context,
366 		     realm->cached_context->seq,
367 		     (unsigned int)realm->cached_context->num_snaps);
368 		return 0;
369 	}
370 
371 	/* alloc new snap context */
372 	err = -ENOMEM;
373 	if (num > (SIZE_MAX - sizeof(*snapc)) / sizeof(u64))
374 		goto fail;
375 	snapc = ceph_create_snap_context(num, GFP_NOFS);
376 	if (!snapc)
377 		goto fail;
378 
379 	/* build (reverse sorted) snap vector */
380 	num = 0;
381 	snapc->seq = realm->seq;
382 	if (parent) {
383 		u32 i;
384 
385 		/* include any of parent's snaps occurring _after_ my
386 		   parent became my parent */
387 		for (i = 0; i < parent->cached_context->num_snaps; i++)
388 			if (parent->cached_context->snaps[i] >=
389 			    realm->parent_since)
390 				snapc->snaps[num++] =
391 					parent->cached_context->snaps[i];
392 		if (parent->cached_context->seq > snapc->seq)
393 			snapc->seq = parent->cached_context->seq;
394 	}
395 	memcpy(snapc->snaps + num, realm->snaps,
396 	       sizeof(u64)*realm->num_snaps);
397 	num += realm->num_snaps;
398 	memcpy(snapc->snaps + num, realm->prior_parent_snaps,
399 	       sizeof(u64)*realm->num_prior_parent_snaps);
400 	num += realm->num_prior_parent_snaps;
401 
402 	sort(snapc->snaps, num, sizeof(u64), cmpu64_rev, NULL);
403 	snapc->num_snaps = num;
404 	dout("%s %llx %p: %p seq %lld (%u snaps)\n", __func__, realm->ino,
405 	     realm, snapc, snapc->seq, (unsigned int) snapc->num_snaps);
406 
407 	ceph_put_snap_context(realm->cached_context);
408 	realm->cached_context = snapc;
409 	/* queue realm for cap_snap creation */
410 	list_add_tail(&realm->dirty_item, dirty_realms);
411 	return 0;
412 
413 fail:
414 	/*
415 	 * if we fail, clear old (incorrect) cached_context... hopefully
416 	 * we'll have better luck building it later
417 	 */
418 	if (realm->cached_context) {
419 		ceph_put_snap_context(realm->cached_context);
420 		realm->cached_context = NULL;
421 	}
422 	pr_err("%s %llx %p fail %d\n", __func__, realm->ino, realm, err);
423 	return err;
424 }
425 
426 /*
427  * rebuild snap context for the given realm and all of its children.
428  */
429 static void rebuild_snap_realms(struct ceph_mds_client *mdsc,
430 				struct ceph_snap_realm *realm,
431 				struct list_head *dirty_realms)
432 {
433 	LIST_HEAD(realm_queue);
434 	int last = 0;
435 	bool skip = false;
436 
437 	list_add_tail(&realm->rebuild_item, &realm_queue);
438 
439 	while (!list_empty(&realm_queue)) {
440 		struct ceph_snap_realm *_realm, *child;
441 
442 		_realm = list_first_entry(&realm_queue,
443 					  struct ceph_snap_realm,
444 					  rebuild_item);
445 
446 		/*
447 		 * If the last building failed dues to memory
448 		 * issue, just empty the realm_queue and return
449 		 * to avoid infinite loop.
450 		 */
451 		if (last < 0) {
452 			list_del_init(&_realm->rebuild_item);
453 			continue;
454 		}
455 
456 		last = build_snap_context(mdsc, _realm, &realm_queue,
457 					  dirty_realms);
458 		dout("%s %llx %p, %s\n", __func__, _realm->ino, _realm,
459 		     last > 0 ? "is deferred" : !last ? "succeeded" : "failed");
460 
461 		/* is any child in the list ? */
462 		list_for_each_entry(child, &_realm->children, child_item) {
463 			if (!list_empty(&child->rebuild_item)) {
464 				skip = true;
465 				break;
466 			}
467 		}
468 
469 		if (!skip) {
470 			list_for_each_entry(child, &_realm->children, child_item)
471 				list_add_tail(&child->rebuild_item, &realm_queue);
472 		}
473 
474 		/* last == 1 means need to build parent first */
475 		if (last <= 0)
476 			list_del_init(&_realm->rebuild_item);
477 	}
478 }
479 
480 
481 /*
482  * helper to allocate and decode an array of snapids.  free prior
483  * instance, if any.
484  */
485 static int dup_array(u64 **dst, __le64 *src, u32 num)
486 {
487 	u32 i;
488 
489 	kfree(*dst);
490 	if (num) {
491 		*dst = kcalloc(num, sizeof(u64), GFP_NOFS);
492 		if (!*dst)
493 			return -ENOMEM;
494 		for (i = 0; i < num; i++)
495 			(*dst)[i] = get_unaligned_le64(src + i);
496 	} else {
497 		*dst = NULL;
498 	}
499 	return 0;
500 }
501 
502 static bool has_new_snaps(struct ceph_snap_context *o,
503 			  struct ceph_snap_context *n)
504 {
505 	if (n->num_snaps == 0)
506 		return false;
507 	/* snaps are in descending order */
508 	return n->snaps[0] > o->seq;
509 }
510 
511 /*
512  * When a snapshot is applied, the size/mtime inode metadata is queued
513  * in a ceph_cap_snap (one for each snapshot) until writeback
514  * completes and the metadata can be flushed back to the MDS.
515  *
516  * However, if a (sync) write is currently in-progress when we apply
517  * the snapshot, we have to wait until the write succeeds or fails
518  * (and a final size/mtime is known).  In this case the
519  * cap_snap->writing = 1, and is said to be "pending."  When the write
520  * finishes, we __ceph_finish_cap_snap().
521  *
522  * Caller must hold snap_rwsem for read (i.e., the realm topology won't
523  * change).
524  */
525 static void ceph_queue_cap_snap(struct ceph_inode_info *ci,
526 				struct ceph_cap_snap **pcapsnap)
527 {
528 	struct inode *inode = &ci->netfs.inode;
529 	struct ceph_snap_context *old_snapc, *new_snapc;
530 	struct ceph_cap_snap *capsnap = *pcapsnap;
531 	struct ceph_buffer *old_blob = NULL;
532 	int used, dirty;
533 
534 	spin_lock(&ci->i_ceph_lock);
535 	used = __ceph_caps_used(ci);
536 	dirty = __ceph_caps_dirty(ci);
537 
538 	old_snapc = ci->i_head_snapc;
539 	new_snapc = ci->i_snap_realm->cached_context;
540 
541 	/*
542 	 * If there is a write in progress, treat that as a dirty Fw,
543 	 * even though it hasn't completed yet; by the time we finish
544 	 * up this capsnap it will be.
545 	 */
546 	if (used & CEPH_CAP_FILE_WR)
547 		dirty |= CEPH_CAP_FILE_WR;
548 
549 	if (__ceph_have_pending_cap_snap(ci)) {
550 		/* there is no point in queuing multiple "pending" cap_snaps,
551 		   as no new writes are allowed to start when pending, so any
552 		   writes in progress now were started before the previous
553 		   cap_snap.  lucky us. */
554 		dout("%s %p %llx.%llx already pending\n",
555 		     __func__, inode, ceph_vinop(inode));
556 		goto update_snapc;
557 	}
558 	if (ci->i_wrbuffer_ref_head == 0 &&
559 	    !(dirty & (CEPH_CAP_ANY_EXCL|CEPH_CAP_FILE_WR))) {
560 		dout("%s %p %llx.%llx nothing dirty|writing\n",
561 		     __func__, inode, ceph_vinop(inode));
562 		goto update_snapc;
563 	}
564 
565 	BUG_ON(!old_snapc);
566 
567 	/*
568 	 * There is no need to send FLUSHSNAP message to MDS if there is
569 	 * no new snapshot. But when there is dirty pages or on-going
570 	 * writes, we still need to create cap_snap. cap_snap is needed
571 	 * by the write path and page writeback path.
572 	 *
573 	 * also see ceph_try_drop_cap_snap()
574 	 */
575 	if (has_new_snaps(old_snapc, new_snapc)) {
576 		if (dirty & (CEPH_CAP_ANY_EXCL|CEPH_CAP_FILE_WR))
577 			capsnap->need_flush = true;
578 	} else {
579 		if (!(used & CEPH_CAP_FILE_WR) &&
580 		    ci->i_wrbuffer_ref_head == 0) {
581 			dout("%s %p %llx.%llx no new_snap|dirty_page|writing\n",
582 			     __func__, inode, ceph_vinop(inode));
583 			goto update_snapc;
584 		}
585 	}
586 
587 	dout("%s %p %llx.%llx cap_snap %p queuing under %p %s %s\n",
588 	     __func__, inode, ceph_vinop(inode), capsnap, old_snapc,
589 	     ceph_cap_string(dirty), capsnap->need_flush ? "" : "no_flush");
590 	ihold(inode);
591 
592 	capsnap->follows = old_snapc->seq;
593 	capsnap->issued = __ceph_caps_issued(ci, NULL);
594 	capsnap->dirty = dirty;
595 
596 	capsnap->mode = inode->i_mode;
597 	capsnap->uid = inode->i_uid;
598 	capsnap->gid = inode->i_gid;
599 
600 	if (dirty & CEPH_CAP_XATTR_EXCL) {
601 		old_blob = __ceph_build_xattrs_blob(ci);
602 		capsnap->xattr_blob =
603 			ceph_buffer_get(ci->i_xattrs.blob);
604 		capsnap->xattr_version = ci->i_xattrs.version;
605 	} else {
606 		capsnap->xattr_blob = NULL;
607 		capsnap->xattr_version = 0;
608 	}
609 
610 	capsnap->inline_data = ci->i_inline_version != CEPH_INLINE_NONE;
611 
612 	/* dirty page count moved from _head to this cap_snap;
613 	   all subsequent writes page dirties occur _after_ this
614 	   snapshot. */
615 	capsnap->dirty_pages = ci->i_wrbuffer_ref_head;
616 	ci->i_wrbuffer_ref_head = 0;
617 	capsnap->context = old_snapc;
618 	list_add_tail(&capsnap->ci_item, &ci->i_cap_snaps);
619 
620 	if (used & CEPH_CAP_FILE_WR) {
621 		dout("%s %p %llx.%llx cap_snap %p snapc %p seq %llu used WR,"
622 		     " now pending\n", __func__, inode, ceph_vinop(inode),
623 		     capsnap, old_snapc, old_snapc->seq);
624 		capsnap->writing = 1;
625 	} else {
626 		/* note mtime, size NOW. */
627 		__ceph_finish_cap_snap(ci, capsnap);
628 	}
629 	*pcapsnap = NULL;
630 	old_snapc = NULL;
631 
632 update_snapc:
633 	if (ci->i_wrbuffer_ref_head == 0 &&
634 	    ci->i_wr_ref == 0 &&
635 	    ci->i_dirty_caps == 0 &&
636 	    ci->i_flushing_caps == 0) {
637 		ci->i_head_snapc = NULL;
638 	} else {
639 		ci->i_head_snapc = ceph_get_snap_context(new_snapc);
640 		dout(" new snapc is %p\n", new_snapc);
641 	}
642 	spin_unlock(&ci->i_ceph_lock);
643 
644 	ceph_buffer_put(old_blob);
645 	ceph_put_snap_context(old_snapc);
646 }
647 
648 /*
649  * Finalize the size, mtime for a cap_snap.. that is, settle on final values
650  * to be used for the snapshot, to be flushed back to the mds.
651  *
652  * If capsnap can now be flushed, add to snap_flush list, and return 1.
653  *
654  * Caller must hold i_ceph_lock.
655  */
656 int __ceph_finish_cap_snap(struct ceph_inode_info *ci,
657 			    struct ceph_cap_snap *capsnap)
658 {
659 	struct inode *inode = &ci->netfs.inode;
660 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
661 
662 	BUG_ON(capsnap->writing);
663 	capsnap->size = i_size_read(inode);
664 	capsnap->mtime = inode->i_mtime;
665 	capsnap->atime = inode->i_atime;
666 	capsnap->ctime = inode_get_ctime(inode);
667 	capsnap->btime = ci->i_btime;
668 	capsnap->change_attr = inode_peek_iversion_raw(inode);
669 	capsnap->time_warp_seq = ci->i_time_warp_seq;
670 	capsnap->truncate_size = ci->i_truncate_size;
671 	capsnap->truncate_seq = ci->i_truncate_seq;
672 	if (capsnap->dirty_pages) {
673 		dout("%s %p %llx.%llx cap_snap %p snapc %p %llu %s s=%llu "
674 		     "still has %d dirty pages\n", __func__, inode,
675 		     ceph_vinop(inode), capsnap, capsnap->context,
676 		     capsnap->context->seq, ceph_cap_string(capsnap->dirty),
677 		     capsnap->size, capsnap->dirty_pages);
678 		return 0;
679 	}
680 
681 	/*
682 	 * Defer flushing the capsnap if the dirty buffer not flushed yet.
683 	 * And trigger to flush the buffer immediately.
684 	 */
685 	if (ci->i_wrbuffer_ref) {
686 		dout("%s %p %llx.%llx cap_snap %p snapc %p %llu %s s=%llu "
687 		     "used WRBUFFER, delaying\n", __func__, inode,
688 		     ceph_vinop(inode), capsnap, capsnap->context,
689 		     capsnap->context->seq, ceph_cap_string(capsnap->dirty),
690 		     capsnap->size);
691 		ceph_queue_writeback(inode);
692 		return 0;
693 	}
694 
695 	ci->i_ceph_flags |= CEPH_I_FLUSH_SNAPS;
696 	dout("%s %p %llx.%llx cap_snap %p snapc %p %llu %s s=%llu\n",
697 	     __func__, inode, ceph_vinop(inode), capsnap, capsnap->context,
698 	     capsnap->context->seq, ceph_cap_string(capsnap->dirty),
699 	     capsnap->size);
700 
701 	spin_lock(&mdsc->snap_flush_lock);
702 	if (list_empty(&ci->i_snap_flush_item)) {
703 		ihold(inode);
704 		list_add_tail(&ci->i_snap_flush_item, &mdsc->snap_flush_list);
705 	}
706 	spin_unlock(&mdsc->snap_flush_lock);
707 	return 1;  /* caller may want to ceph_flush_snaps */
708 }
709 
710 /*
711  * Queue cap_snaps for snap writeback for this realm and its children.
712  * Called under snap_rwsem, so realm topology won't change.
713  */
714 static void queue_realm_cap_snaps(struct ceph_mds_client *mdsc,
715 				  struct ceph_snap_realm *realm)
716 {
717 	struct ceph_inode_info *ci;
718 	struct inode *lastinode = NULL;
719 	struct ceph_cap_snap *capsnap = NULL;
720 
721 	dout("%s %p %llx inode\n", __func__, realm, realm->ino);
722 
723 	spin_lock(&realm->inodes_with_caps_lock);
724 	list_for_each_entry(ci, &realm->inodes_with_caps, i_snap_realm_item) {
725 		struct inode *inode = igrab(&ci->netfs.inode);
726 		if (!inode)
727 			continue;
728 		spin_unlock(&realm->inodes_with_caps_lock);
729 		iput(lastinode);
730 		lastinode = inode;
731 
732 		/*
733 		 * Allocate the capsnap memory outside of ceph_queue_cap_snap()
734 		 * to reduce very possible but unnecessary frequently memory
735 		 * allocate/free in this loop.
736 		 */
737 		if (!capsnap) {
738 			capsnap = kmem_cache_zalloc(ceph_cap_snap_cachep, GFP_NOFS);
739 			if (!capsnap) {
740 				pr_err("ENOMEM allocating ceph_cap_snap on %p\n",
741 				       inode);
742 				return;
743 			}
744 		}
745 		capsnap->cap_flush.is_capsnap = true;
746 		refcount_set(&capsnap->nref, 1);
747 		INIT_LIST_HEAD(&capsnap->cap_flush.i_list);
748 		INIT_LIST_HEAD(&capsnap->cap_flush.g_list);
749 		INIT_LIST_HEAD(&capsnap->ci_item);
750 
751 		ceph_queue_cap_snap(ci, &capsnap);
752 		spin_lock(&realm->inodes_with_caps_lock);
753 	}
754 	spin_unlock(&realm->inodes_with_caps_lock);
755 	iput(lastinode);
756 
757 	if (capsnap)
758 		kmem_cache_free(ceph_cap_snap_cachep, capsnap);
759 	dout("%s %p %llx done\n", __func__, realm, realm->ino);
760 }
761 
762 /*
763  * Parse and apply a snapblob "snap trace" from the MDS.  This specifies
764  * the snap realm parameters from a given realm and all of its ancestors,
765  * up to the root.
766  *
767  * Caller must hold snap_rwsem for write.
768  */
769 int ceph_update_snap_trace(struct ceph_mds_client *mdsc,
770 			   void *p, void *e, bool deletion,
771 			   struct ceph_snap_realm **realm_ret)
772 {
773 	struct ceph_mds_snap_realm *ri;    /* encoded */
774 	__le64 *snaps;                     /* encoded */
775 	__le64 *prior_parent_snaps;        /* encoded */
776 	struct ceph_snap_realm *realm;
777 	struct ceph_snap_realm *first_realm = NULL;
778 	struct ceph_snap_realm *realm_to_rebuild = NULL;
779 	struct ceph_client *client = mdsc->fsc->client;
780 	int rebuild_snapcs;
781 	int err = -ENOMEM;
782 	int ret;
783 	LIST_HEAD(dirty_realms);
784 
785 	lockdep_assert_held_write(&mdsc->snap_rwsem);
786 
787 	dout("%s deletion=%d\n", __func__, deletion);
788 more:
789 	realm = NULL;
790 	rebuild_snapcs = 0;
791 	ceph_decode_need(&p, e, sizeof(*ri), bad);
792 	ri = p;
793 	p += sizeof(*ri);
794 	ceph_decode_need(&p, e, sizeof(u64)*(le32_to_cpu(ri->num_snaps) +
795 			    le32_to_cpu(ri->num_prior_parent_snaps)), bad);
796 	snaps = p;
797 	p += sizeof(u64) * le32_to_cpu(ri->num_snaps);
798 	prior_parent_snaps = p;
799 	p += sizeof(u64) * le32_to_cpu(ri->num_prior_parent_snaps);
800 
801 	realm = ceph_lookup_snap_realm(mdsc, le64_to_cpu(ri->ino));
802 	if (!realm) {
803 		realm = ceph_create_snap_realm(mdsc, le64_to_cpu(ri->ino));
804 		if (IS_ERR(realm)) {
805 			err = PTR_ERR(realm);
806 			goto fail;
807 		}
808 	}
809 
810 	/* ensure the parent is correct */
811 	err = adjust_snap_realm_parent(mdsc, realm, le64_to_cpu(ri->parent));
812 	if (err < 0)
813 		goto fail;
814 	rebuild_snapcs += err;
815 
816 	if (le64_to_cpu(ri->seq) > realm->seq) {
817 		dout("%s updating %llx %p %lld -> %lld\n", __func__,
818 		     realm->ino, realm, realm->seq, le64_to_cpu(ri->seq));
819 		/* update realm parameters, snap lists */
820 		realm->seq = le64_to_cpu(ri->seq);
821 		realm->created = le64_to_cpu(ri->created);
822 		realm->parent_since = le64_to_cpu(ri->parent_since);
823 
824 		realm->num_snaps = le32_to_cpu(ri->num_snaps);
825 		err = dup_array(&realm->snaps, snaps, realm->num_snaps);
826 		if (err < 0)
827 			goto fail;
828 
829 		realm->num_prior_parent_snaps =
830 			le32_to_cpu(ri->num_prior_parent_snaps);
831 		err = dup_array(&realm->prior_parent_snaps, prior_parent_snaps,
832 				realm->num_prior_parent_snaps);
833 		if (err < 0)
834 			goto fail;
835 
836 		if (realm->seq > mdsc->last_snap_seq)
837 			mdsc->last_snap_seq = realm->seq;
838 
839 		rebuild_snapcs = 1;
840 	} else if (!realm->cached_context) {
841 		dout("%s %llx %p seq %lld new\n", __func__,
842 		     realm->ino, realm, realm->seq);
843 		rebuild_snapcs = 1;
844 	} else {
845 		dout("%s %llx %p seq %lld unchanged\n", __func__,
846 		     realm->ino, realm, realm->seq);
847 	}
848 
849 	dout("done with %llx %p, rebuild_snapcs=%d, %p %p\n", realm->ino,
850 	     realm, rebuild_snapcs, p, e);
851 
852 	/*
853 	 * this will always track the uppest parent realm from which
854 	 * we need to rebuild the snapshot contexts _downward_ in
855 	 * hierarchy.
856 	 */
857 	if (rebuild_snapcs)
858 		realm_to_rebuild = realm;
859 
860 	/* rebuild_snapcs when we reach the _end_ (root) of the trace */
861 	if (realm_to_rebuild && p >= e)
862 		rebuild_snap_realms(mdsc, realm_to_rebuild, &dirty_realms);
863 
864 	if (!first_realm)
865 		first_realm = realm;
866 	else
867 		ceph_put_snap_realm(mdsc, realm);
868 
869 	if (p < e)
870 		goto more;
871 
872 	/*
873 	 * queue cap snaps _after_ we've built the new snap contexts,
874 	 * so that i_head_snapc can be set appropriately.
875 	 */
876 	while (!list_empty(&dirty_realms)) {
877 		realm = list_first_entry(&dirty_realms, struct ceph_snap_realm,
878 					 dirty_item);
879 		list_del_init(&realm->dirty_item);
880 		queue_realm_cap_snaps(mdsc, realm);
881 	}
882 
883 	if (realm_ret)
884 		*realm_ret = first_realm;
885 	else
886 		ceph_put_snap_realm(mdsc, first_realm);
887 
888 	__cleanup_empty_realms(mdsc);
889 	return 0;
890 
891 bad:
892 	err = -EIO;
893 fail:
894 	if (realm && !IS_ERR(realm))
895 		ceph_put_snap_realm(mdsc, realm);
896 	if (first_realm)
897 		ceph_put_snap_realm(mdsc, first_realm);
898 	pr_err("%s error %d\n", __func__, err);
899 
900 	/*
901 	 * When receiving a corrupted snap trace we don't know what
902 	 * exactly has happened in MDS side. And we shouldn't continue
903 	 * writing to OSD, which may corrupt the snapshot contents.
904 	 *
905 	 * Just try to blocklist this kclient and then this kclient
906 	 * must be remounted to continue after the corrupted metadata
907 	 * fixed in the MDS side.
908 	 */
909 	WRITE_ONCE(mdsc->fsc->mount_state, CEPH_MOUNT_FENCE_IO);
910 	ret = ceph_monc_blocklist_add(&client->monc, &client->msgr.inst.addr);
911 	if (ret)
912 		pr_err("%s failed to blocklist %s: %d\n", __func__,
913 		       ceph_pr_addr(&client->msgr.inst.addr), ret);
914 
915 	WARN(1, "%s: %s%sdo remount to continue%s",
916 	     __func__, ret ? "" : ceph_pr_addr(&client->msgr.inst.addr),
917 	     ret ? "" : " was blocklisted, ",
918 	     err == -EIO ? " after corrupted snaptrace is fixed" : "");
919 
920 	return err;
921 }
922 
923 
924 /*
925  * Send any cap_snaps that are queued for flush.  Try to carry
926  * s_mutex across multiple snap flushes to avoid locking overhead.
927  *
928  * Caller holds no locks.
929  */
930 static void flush_snaps(struct ceph_mds_client *mdsc)
931 {
932 	struct ceph_inode_info *ci;
933 	struct inode *inode;
934 	struct ceph_mds_session *session = NULL;
935 
936 	dout("%s\n", __func__);
937 	spin_lock(&mdsc->snap_flush_lock);
938 	while (!list_empty(&mdsc->snap_flush_list)) {
939 		ci = list_first_entry(&mdsc->snap_flush_list,
940 				struct ceph_inode_info, i_snap_flush_item);
941 		inode = &ci->netfs.inode;
942 		ihold(inode);
943 		spin_unlock(&mdsc->snap_flush_lock);
944 		ceph_flush_snaps(ci, &session);
945 		iput(inode);
946 		spin_lock(&mdsc->snap_flush_lock);
947 	}
948 	spin_unlock(&mdsc->snap_flush_lock);
949 
950 	ceph_put_mds_session(session);
951 	dout("%s done\n", __func__);
952 }
953 
954 /**
955  * ceph_change_snap_realm - change the snap_realm for an inode
956  * @inode: inode to move to new snap realm
957  * @realm: new realm to move inode into (may be NULL)
958  *
959  * Detach an inode from its old snaprealm (if any) and attach it to
960  * the new snaprealm (if any). The old snap realm reference held by
961  * the inode is put. If realm is non-NULL, then the caller's reference
962  * to it is taken over by the inode.
963  */
964 void ceph_change_snap_realm(struct inode *inode, struct ceph_snap_realm *realm)
965 {
966 	struct ceph_inode_info *ci = ceph_inode(inode);
967 	struct ceph_mds_client *mdsc = ceph_inode_to_fs_client(inode)->mdsc;
968 	struct ceph_snap_realm *oldrealm = ci->i_snap_realm;
969 
970 	lockdep_assert_held(&ci->i_ceph_lock);
971 
972 	if (oldrealm) {
973 		spin_lock(&oldrealm->inodes_with_caps_lock);
974 		list_del_init(&ci->i_snap_realm_item);
975 		if (oldrealm->ino == ci->i_vino.ino)
976 			oldrealm->inode = NULL;
977 		spin_unlock(&oldrealm->inodes_with_caps_lock);
978 		ceph_put_snap_realm(mdsc, oldrealm);
979 	}
980 
981 	ci->i_snap_realm = realm;
982 
983 	if (realm) {
984 		spin_lock(&realm->inodes_with_caps_lock);
985 		list_add(&ci->i_snap_realm_item, &realm->inodes_with_caps);
986 		if (realm->ino == ci->i_vino.ino)
987 			realm->inode = inode;
988 		spin_unlock(&realm->inodes_with_caps_lock);
989 	}
990 }
991 
992 /*
993  * Handle a snap notification from the MDS.
994  *
995  * This can take two basic forms: the simplest is just a snap creation
996  * or deletion notification on an existing realm.  This should update the
997  * realm and its children.
998  *
999  * The more difficult case is realm creation, due to snap creation at a
1000  * new point in the file hierarchy, or due to a rename that moves a file or
1001  * directory into another realm.
1002  */
1003 void ceph_handle_snap(struct ceph_mds_client *mdsc,
1004 		      struct ceph_mds_session *session,
1005 		      struct ceph_msg *msg)
1006 {
1007 	struct super_block *sb = mdsc->fsc->sb;
1008 	int mds = session->s_mds;
1009 	u64 split;
1010 	int op;
1011 	int trace_len;
1012 	struct ceph_snap_realm *realm = NULL;
1013 	void *p = msg->front.iov_base;
1014 	void *e = p + msg->front.iov_len;
1015 	struct ceph_mds_snap_head *h;
1016 	int num_split_inos, num_split_realms;
1017 	__le64 *split_inos = NULL, *split_realms = NULL;
1018 	int i;
1019 	int locked_rwsem = 0;
1020 	bool close_sessions = false;
1021 
1022 	if (!ceph_inc_mds_stopping_blocker(mdsc, session))
1023 		return;
1024 
1025 	/* decode */
1026 	if (msg->front.iov_len < sizeof(*h))
1027 		goto bad;
1028 	h = p;
1029 	op = le32_to_cpu(h->op);
1030 	split = le64_to_cpu(h->split);   /* non-zero if we are splitting an
1031 					  * existing realm */
1032 	num_split_inos = le32_to_cpu(h->num_split_inos);
1033 	num_split_realms = le32_to_cpu(h->num_split_realms);
1034 	trace_len = le32_to_cpu(h->trace_len);
1035 	p += sizeof(*h);
1036 
1037 	dout("%s from mds%d op %s split %llx tracelen %d\n", __func__,
1038 	     mds, ceph_snap_op_name(op), split, trace_len);
1039 
1040 	down_write(&mdsc->snap_rwsem);
1041 	locked_rwsem = 1;
1042 
1043 	if (op == CEPH_SNAP_OP_SPLIT) {
1044 		struct ceph_mds_snap_realm *ri;
1045 
1046 		/*
1047 		 * A "split" breaks part of an existing realm off into
1048 		 * a new realm.  The MDS provides a list of inodes
1049 		 * (with caps) and child realms that belong to the new
1050 		 * child.
1051 		 */
1052 		split_inos = p;
1053 		p += sizeof(u64) * num_split_inos;
1054 		split_realms = p;
1055 		p += sizeof(u64) * num_split_realms;
1056 		ceph_decode_need(&p, e, sizeof(*ri), bad);
1057 		/* we will peek at realm info here, but will _not_
1058 		 * advance p, as the realm update will occur below in
1059 		 * ceph_update_snap_trace. */
1060 		ri = p;
1061 
1062 		realm = ceph_lookup_snap_realm(mdsc, split);
1063 		if (!realm) {
1064 			realm = ceph_create_snap_realm(mdsc, split);
1065 			if (IS_ERR(realm))
1066 				goto out;
1067 		}
1068 
1069 		dout("splitting snap_realm %llx %p\n", realm->ino, realm);
1070 		for (i = 0; i < num_split_inos; i++) {
1071 			struct ceph_vino vino = {
1072 				.ino = le64_to_cpu(split_inos[i]),
1073 				.snap = CEPH_NOSNAP,
1074 			};
1075 			struct inode *inode = ceph_find_inode(sb, vino);
1076 			struct ceph_inode_info *ci;
1077 
1078 			if (!inode)
1079 				continue;
1080 			ci = ceph_inode(inode);
1081 
1082 			spin_lock(&ci->i_ceph_lock);
1083 			if (!ci->i_snap_realm)
1084 				goto skip_inode;
1085 			/*
1086 			 * If this inode belongs to a realm that was
1087 			 * created after our new realm, we experienced
1088 			 * a race (due to another split notifications
1089 			 * arriving from a different MDS).  So skip
1090 			 * this inode.
1091 			 */
1092 			if (ci->i_snap_realm->created >
1093 			    le64_to_cpu(ri->created)) {
1094 				dout(" leaving %p %llx.%llx in newer realm %llx %p\n",
1095 				     inode, ceph_vinop(inode), ci->i_snap_realm->ino,
1096 				     ci->i_snap_realm);
1097 				goto skip_inode;
1098 			}
1099 			dout(" will move %p %llx.%llx to split realm %llx %p\n",
1100 			     inode, ceph_vinop(inode), realm->ino, realm);
1101 
1102 			ceph_get_snap_realm(mdsc, realm);
1103 			ceph_change_snap_realm(inode, realm);
1104 			spin_unlock(&ci->i_ceph_lock);
1105 			iput(inode);
1106 			continue;
1107 
1108 skip_inode:
1109 			spin_unlock(&ci->i_ceph_lock);
1110 			iput(inode);
1111 		}
1112 
1113 		/* we may have taken some of the old realm's children. */
1114 		for (i = 0; i < num_split_realms; i++) {
1115 			struct ceph_snap_realm *child =
1116 				__lookup_snap_realm(mdsc,
1117 					   le64_to_cpu(split_realms[i]));
1118 			if (!child)
1119 				continue;
1120 			adjust_snap_realm_parent(mdsc, child, realm->ino);
1121 		}
1122 	} else {
1123 		/*
1124 		 * In the non-split case both 'num_split_inos' and
1125 		 * 'num_split_realms' should be 0, making this a no-op.
1126 		 * However the MDS happens to populate 'split_realms' list
1127 		 * in one of the UPDATE op cases by mistake.
1128 		 *
1129 		 * Skip both lists just in case to ensure that 'p' is
1130 		 * positioned at the start of realm info, as expected by
1131 		 * ceph_update_snap_trace().
1132 		 */
1133 		p += sizeof(u64) * num_split_inos;
1134 		p += sizeof(u64) * num_split_realms;
1135 	}
1136 
1137 	/*
1138 	 * update using the provided snap trace. if we are deleting a
1139 	 * snap, we can avoid queueing cap_snaps.
1140 	 */
1141 	if (ceph_update_snap_trace(mdsc, p, e,
1142 				   op == CEPH_SNAP_OP_DESTROY,
1143 				   NULL)) {
1144 		close_sessions = true;
1145 		goto bad;
1146 	}
1147 
1148 	if (op == CEPH_SNAP_OP_SPLIT)
1149 		/* we took a reference when we created the realm, above */
1150 		ceph_put_snap_realm(mdsc, realm);
1151 
1152 	__cleanup_empty_realms(mdsc);
1153 
1154 	up_write(&mdsc->snap_rwsem);
1155 
1156 	flush_snaps(mdsc);
1157 	ceph_dec_mds_stopping_blocker(mdsc);
1158 	return;
1159 
1160 bad:
1161 	pr_err("%s corrupt snap message from mds%d\n", __func__, mds);
1162 	ceph_msg_dump(msg);
1163 out:
1164 	if (locked_rwsem)
1165 		up_write(&mdsc->snap_rwsem);
1166 
1167 	ceph_dec_mds_stopping_blocker(mdsc);
1168 
1169 	if (close_sessions)
1170 		ceph_mdsc_close_sessions(mdsc);
1171 	return;
1172 }
1173 
1174 struct ceph_snapid_map* ceph_get_snapid_map(struct ceph_mds_client *mdsc,
1175 					    u64 snap)
1176 {
1177 	struct ceph_snapid_map *sm, *exist;
1178 	struct rb_node **p, *parent;
1179 	int ret;
1180 
1181 	exist = NULL;
1182 	spin_lock(&mdsc->snapid_map_lock);
1183 	p = &mdsc->snapid_map_tree.rb_node;
1184 	while (*p) {
1185 		exist = rb_entry(*p, struct ceph_snapid_map, node);
1186 		if (snap > exist->snap) {
1187 			p = &(*p)->rb_left;
1188 		} else if (snap < exist->snap) {
1189 			p = &(*p)->rb_right;
1190 		} else {
1191 			if (atomic_inc_return(&exist->ref) == 1)
1192 				list_del_init(&exist->lru);
1193 			break;
1194 		}
1195 		exist = NULL;
1196 	}
1197 	spin_unlock(&mdsc->snapid_map_lock);
1198 	if (exist) {
1199 		dout("%s found snapid map %llx -> %x\n", __func__,
1200 		     exist->snap, exist->dev);
1201 		return exist;
1202 	}
1203 
1204 	sm = kmalloc(sizeof(*sm), GFP_NOFS);
1205 	if (!sm)
1206 		return NULL;
1207 
1208 	ret = get_anon_bdev(&sm->dev);
1209 	if (ret < 0) {
1210 		kfree(sm);
1211 		return NULL;
1212 	}
1213 
1214 	INIT_LIST_HEAD(&sm->lru);
1215 	atomic_set(&sm->ref, 1);
1216 	sm->snap = snap;
1217 
1218 	exist = NULL;
1219 	parent = NULL;
1220 	p = &mdsc->snapid_map_tree.rb_node;
1221 	spin_lock(&mdsc->snapid_map_lock);
1222 	while (*p) {
1223 		parent = *p;
1224 		exist = rb_entry(*p, struct ceph_snapid_map, node);
1225 		if (snap > exist->snap)
1226 			p = &(*p)->rb_left;
1227 		else if (snap < exist->snap)
1228 			p = &(*p)->rb_right;
1229 		else
1230 			break;
1231 		exist = NULL;
1232 	}
1233 	if (exist) {
1234 		if (atomic_inc_return(&exist->ref) == 1)
1235 			list_del_init(&exist->lru);
1236 	} else {
1237 		rb_link_node(&sm->node, parent, p);
1238 		rb_insert_color(&sm->node, &mdsc->snapid_map_tree);
1239 	}
1240 	spin_unlock(&mdsc->snapid_map_lock);
1241 	if (exist) {
1242 		free_anon_bdev(sm->dev);
1243 		kfree(sm);
1244 		dout("%s found snapid map %llx -> %x\n", __func__,
1245 		     exist->snap, exist->dev);
1246 		return exist;
1247 	}
1248 
1249 	dout("%s create snapid map %llx -> %x\n", __func__,
1250 	     sm->snap, sm->dev);
1251 	return sm;
1252 }
1253 
1254 void ceph_put_snapid_map(struct ceph_mds_client* mdsc,
1255 			 struct ceph_snapid_map *sm)
1256 {
1257 	if (!sm)
1258 		return;
1259 	if (atomic_dec_and_lock(&sm->ref, &mdsc->snapid_map_lock)) {
1260 		if (!RB_EMPTY_NODE(&sm->node)) {
1261 			sm->last_used = jiffies;
1262 			list_add_tail(&sm->lru, &mdsc->snapid_map_lru);
1263 			spin_unlock(&mdsc->snapid_map_lock);
1264 		} else {
1265 			/* already cleaned up by
1266 			 * ceph_cleanup_snapid_map() */
1267 			spin_unlock(&mdsc->snapid_map_lock);
1268 			kfree(sm);
1269 		}
1270 	}
1271 }
1272 
1273 void ceph_trim_snapid_map(struct ceph_mds_client *mdsc)
1274 {
1275 	struct ceph_snapid_map *sm;
1276 	unsigned long now;
1277 	LIST_HEAD(to_free);
1278 
1279 	spin_lock(&mdsc->snapid_map_lock);
1280 	now = jiffies;
1281 
1282 	while (!list_empty(&mdsc->snapid_map_lru)) {
1283 		sm = list_first_entry(&mdsc->snapid_map_lru,
1284 				      struct ceph_snapid_map, lru);
1285 		if (time_after(sm->last_used + CEPH_SNAPID_MAP_TIMEOUT, now))
1286 			break;
1287 
1288 		rb_erase(&sm->node, &mdsc->snapid_map_tree);
1289 		list_move(&sm->lru, &to_free);
1290 	}
1291 	spin_unlock(&mdsc->snapid_map_lock);
1292 
1293 	while (!list_empty(&to_free)) {
1294 		sm = list_first_entry(&to_free, struct ceph_snapid_map, lru);
1295 		list_del(&sm->lru);
1296 		dout("trim snapid map %llx -> %x\n", sm->snap, sm->dev);
1297 		free_anon_bdev(sm->dev);
1298 		kfree(sm);
1299 	}
1300 }
1301 
1302 void ceph_cleanup_snapid_map(struct ceph_mds_client *mdsc)
1303 {
1304 	struct ceph_snapid_map *sm;
1305 	struct rb_node *p;
1306 	LIST_HEAD(to_free);
1307 
1308 	spin_lock(&mdsc->snapid_map_lock);
1309 	while ((p = rb_first(&mdsc->snapid_map_tree))) {
1310 		sm = rb_entry(p, struct ceph_snapid_map, node);
1311 		rb_erase(p, &mdsc->snapid_map_tree);
1312 		RB_CLEAR_NODE(p);
1313 		list_move(&sm->lru, &to_free);
1314 	}
1315 	spin_unlock(&mdsc->snapid_map_lock);
1316 
1317 	while (!list_empty(&to_free)) {
1318 		sm = list_first_entry(&to_free, struct ceph_snapid_map, lru);
1319 		list_del(&sm->lru);
1320 		free_anon_bdev(sm->dev);
1321 		if (WARN_ON_ONCE(atomic_read(&sm->ref))) {
1322 			pr_err("snapid map %llx -> %x still in use\n",
1323 			       sm->snap, sm->dev);
1324 		}
1325 		kfree(sm);
1326 	}
1327 }
1328