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