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