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