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