]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/buckets.c
Update bcachefs sources to b47904df3c bcachefs: Clear BCH_FEATURE_extents_above_btree...
[bcachefs-tools-debian] / libbcachefs / buckets.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Code for manipulating bucket marks for garbage collection.
4  *
5  * Copyright 2014 Datera, Inc.
6  *
7  * Bucket states:
8  * - free bucket: mark == 0
9  *   The bucket contains no data and will not be read
10  *
11  * - allocator bucket: owned_by_allocator == 1
12  *   The bucket is on a free list, or it is an open bucket
13  *
14  * - cached bucket: owned_by_allocator == 0 &&
15  *                  dirty_sectors == 0 &&
16  *                  cached_sectors > 0
17  *   The bucket contains data but may be safely discarded as there are
18  *   enough replicas of the data on other cache devices, or it has been
19  *   written back to the backing device
20  *
21  * - dirty bucket: owned_by_allocator == 0 &&
22  *                 dirty_sectors > 0
23  *   The bucket contains data that we must not discard (either only copy,
24  *   or one of the 'main copies' for data requiring multiple replicas)
25  *
26  * - metadata bucket: owned_by_allocator == 0 && is_metadata == 1
27  *   This is a btree node, journal or gen/prio bucket
28  *
29  * Lifecycle:
30  *
31  * bucket invalidated => bucket on freelist => open bucket =>
32  *     [dirty bucket =>] cached bucket => bucket invalidated => ...
33  *
34  * Note that cache promotion can skip the dirty bucket step, as data
35  * is copied from a deeper tier to a shallower tier, onto a cached
36  * bucket.
37  * Note also that a cached bucket can spontaneously become dirty --
38  * see below.
39  *
40  * Only a traversal of the key space can determine whether a bucket is
41  * truly dirty or cached.
42  *
43  * Transitions:
44  *
45  * - free => allocator: bucket was invalidated
46  * - cached => allocator: bucket was invalidated
47  *
48  * - allocator => dirty: open bucket was filled up
49  * - allocator => cached: open bucket was filled up
50  * - allocator => metadata: metadata was allocated
51  *
52  * - dirty => cached: dirty sectors were copied to a deeper tier
53  * - dirty => free: dirty sectors were overwritten or moved (copy gc)
54  * - cached => free: cached sectors were overwritten
55  *
56  * - metadata => free: metadata was freed
57  *
58  * Oddities:
59  * - cached => dirty: a device was removed so formerly replicated data
60  *                    is no longer sufficiently replicated
61  * - free => cached: cannot happen
62  * - free => dirty: cannot happen
63  * - free => metadata: cannot happen
64  */
65
66 #include "bcachefs.h"
67 #include "alloc_background.h"
68 #include "bset.h"
69 #include "btree_gc.h"
70 #include "btree_update.h"
71 #include "buckets.h"
72 #include "ec.h"
73 #include "error.h"
74 #include "movinggc.h"
75 #include "replicas.h"
76
77 #include <linux/preempt.h>
78 #include <trace/events/bcachefs.h>
79
80 /*
81  * Clear journal_seq_valid for buckets for which it's not needed, to prevent
82  * wraparound:
83  */
84 void bch2_bucket_seq_cleanup(struct bch_fs *c)
85 {
86         u64 journal_seq = atomic64_read(&c->journal.seq);
87         u16 last_seq_ondisk = c->journal.last_seq_ondisk;
88         struct bch_dev *ca;
89         struct bucket_array *buckets;
90         struct bucket *g;
91         struct bucket_mark m;
92         unsigned i;
93
94         if (journal_seq - c->last_bucket_seq_cleanup <
95             (1U << (BUCKET_JOURNAL_SEQ_BITS - 2)))
96                 return;
97
98         c->last_bucket_seq_cleanup = journal_seq;
99
100         for_each_member_device(ca, c, i) {
101                 down_read(&ca->bucket_lock);
102                 buckets = bucket_array(ca);
103
104                 for_each_bucket(g, buckets) {
105                         bucket_cmpxchg(g, m, ({
106                                 if (!m.journal_seq_valid ||
107                                     bucket_needs_journal_commit(m, last_seq_ondisk))
108                                         break;
109
110                                 m.journal_seq_valid = 0;
111                         }));
112                 }
113                 up_read(&ca->bucket_lock);
114         }
115 }
116
117 void bch2_fs_usage_initialize(struct bch_fs *c)
118 {
119         struct bch_fs_usage *usage;
120         unsigned i;
121
122         percpu_down_write(&c->mark_lock);
123         usage = c->usage_base;
124
125         bch2_fs_usage_acc_to_base(c, 0);
126         bch2_fs_usage_acc_to_base(c, 1);
127
128         for (i = 0; i < BCH_REPLICAS_MAX; i++)
129                 usage->reserved += usage->persistent_reserved[i];
130
131         for (i = 0; i < c->replicas.nr; i++) {
132                 struct bch_replicas_entry *e =
133                         cpu_replicas_entry(&c->replicas, i);
134
135                 switch (e->data_type) {
136                 case BCH_DATA_BTREE:
137                         usage->btree    += usage->replicas[i];
138                         break;
139                 case BCH_DATA_USER:
140                         usage->data     += usage->replicas[i];
141                         break;
142                 case BCH_DATA_CACHED:
143                         usage->cached   += usage->replicas[i];
144                         break;
145                 }
146         }
147
148         percpu_up_write(&c->mark_lock);
149 }
150
151 void bch2_fs_usage_scratch_put(struct bch_fs *c, struct bch_fs_usage *fs_usage)
152 {
153         if (fs_usage == c->usage_scratch)
154                 mutex_unlock(&c->usage_scratch_lock);
155         else
156                 kfree(fs_usage);
157 }
158
159 struct bch_fs_usage *bch2_fs_usage_scratch_get(struct bch_fs *c)
160 {
161         struct bch_fs_usage *ret;
162         unsigned bytes = fs_usage_u64s(c) * sizeof(u64);
163
164         ret = kzalloc(bytes, GFP_NOWAIT|__GFP_NOWARN);
165         if (ret)
166                 return ret;
167
168         if (mutex_trylock(&c->usage_scratch_lock))
169                 goto out_pool;
170
171         ret = kzalloc(bytes, GFP_NOFS);
172         if (ret)
173                 return ret;
174
175         mutex_lock(&c->usage_scratch_lock);
176 out_pool:
177         ret = c->usage_scratch;
178         memset(ret, 0, bytes);
179         return ret;
180 }
181
182 struct bch_dev_usage bch2_dev_usage_read(struct bch_fs *c, struct bch_dev *ca)
183 {
184         struct bch_dev_usage ret;
185
186         memset(&ret, 0, sizeof(ret));
187         acc_u64s_percpu((u64 *) &ret,
188                         (u64 __percpu *) ca->usage[0],
189                         sizeof(ret) / sizeof(u64));
190
191         return ret;
192 }
193
194 static inline struct bch_fs_usage *fs_usage_ptr(struct bch_fs *c,
195                                                 unsigned journal_seq,
196                                                 bool gc)
197 {
198         return this_cpu_ptr(gc
199                             ? c->usage_gc
200                             : c->usage[journal_seq & 1]);
201 }
202
203 u64 bch2_fs_usage_read_one(struct bch_fs *c, u64 *v)
204 {
205         ssize_t offset = v - (u64 *) c->usage_base;
206         unsigned seq;
207         u64 ret;
208
209         BUG_ON(offset < 0 || offset >= fs_usage_u64s(c));
210         percpu_rwsem_assert_held(&c->mark_lock);
211
212         do {
213                 seq = read_seqcount_begin(&c->usage_lock);
214                 ret = *v +
215                         percpu_u64_get((u64 __percpu *) c->usage[0] + offset) +
216                         percpu_u64_get((u64 __percpu *) c->usage[1] + offset);
217         } while (read_seqcount_retry(&c->usage_lock, seq));
218
219         return ret;
220 }
221
222 struct bch_fs_usage *bch2_fs_usage_read(struct bch_fs *c)
223 {
224         struct bch_fs_usage *ret;
225         unsigned seq, v, u64s = fs_usage_u64s(c);
226 retry:
227         ret = kmalloc(u64s * sizeof(u64), GFP_NOFS);
228         if (unlikely(!ret))
229                 return NULL;
230
231         percpu_down_read(&c->mark_lock);
232
233         v = fs_usage_u64s(c);
234         if (unlikely(u64s != v)) {
235                 u64s = v;
236                 percpu_up_read(&c->mark_lock);
237                 kfree(ret);
238                 goto retry;
239         }
240
241         do {
242                 seq = read_seqcount_begin(&c->usage_lock);
243                 memcpy(ret, c->usage_base, u64s * sizeof(u64));
244                 acc_u64s_percpu((u64 *) ret, (u64 __percpu *) c->usage[0], u64s);
245                 acc_u64s_percpu((u64 *) ret, (u64 __percpu *) c->usage[1], u64s);
246         } while (read_seqcount_retry(&c->usage_lock, seq));
247
248         return ret;
249 }
250
251 void bch2_fs_usage_acc_to_base(struct bch_fs *c, unsigned idx)
252 {
253         unsigned u64s = fs_usage_u64s(c);
254
255         BUG_ON(idx >= 2);
256
257         write_seqcount_begin(&c->usage_lock);
258
259         acc_u64s_percpu((u64 *) c->usage_base,
260                         (u64 __percpu *) c->usage[idx], u64s);
261         percpu_memset(c->usage[idx], 0, u64s * sizeof(u64));
262
263         write_seqcount_end(&c->usage_lock);
264 }
265
266 void bch2_fs_usage_to_text(struct printbuf *out,
267                            struct bch_fs *c,
268                            struct bch_fs_usage *fs_usage)
269 {
270         unsigned i;
271
272         pr_buf(out, "capacity:\t\t\t%llu\n", c->capacity);
273
274         pr_buf(out, "hidden:\t\t\t\t%llu\n",
275                fs_usage->hidden);
276         pr_buf(out, "data:\t\t\t\t%llu\n",
277                fs_usage->data);
278         pr_buf(out, "cached:\t\t\t\t%llu\n",
279                fs_usage->cached);
280         pr_buf(out, "reserved:\t\t\t%llu\n",
281                fs_usage->reserved);
282         pr_buf(out, "nr_inodes:\t\t\t%llu\n",
283                fs_usage->nr_inodes);
284         pr_buf(out, "online reserved:\t\t%llu\n",
285                fs_usage->online_reserved);
286
287         for (i = 0;
288              i < ARRAY_SIZE(fs_usage->persistent_reserved);
289              i++) {
290                 pr_buf(out, "%u replicas:\n", i + 1);
291                 pr_buf(out, "\treserved:\t\t%llu\n",
292                        fs_usage->persistent_reserved[i]);
293         }
294
295         for (i = 0; i < c->replicas.nr; i++) {
296                 struct bch_replicas_entry *e =
297                         cpu_replicas_entry(&c->replicas, i);
298
299                 pr_buf(out, "\t");
300                 bch2_replicas_entry_to_text(out, e);
301                 pr_buf(out, ":\t%llu\n", fs_usage->replicas[i]);
302         }
303 }
304
305 #define RESERVE_FACTOR  6
306
307 static u64 reserve_factor(u64 r)
308 {
309         return r + (round_up(r, (1 << RESERVE_FACTOR)) >> RESERVE_FACTOR);
310 }
311
312 static u64 avail_factor(u64 r)
313 {
314         return (r << RESERVE_FACTOR) / ((1 << RESERVE_FACTOR) + 1);
315 }
316
317 u64 bch2_fs_sectors_used(struct bch_fs *c, struct bch_fs_usage *fs_usage)
318 {
319         return min(fs_usage->hidden +
320                    fs_usage->btree +
321                    fs_usage->data +
322                    reserve_factor(fs_usage->reserved +
323                                   fs_usage->online_reserved),
324                    c->capacity);
325 }
326
327 static struct bch_fs_usage_short
328 __bch2_fs_usage_read_short(struct bch_fs *c)
329 {
330         struct bch_fs_usage_short ret;
331         u64 data, reserved;
332
333         ret.capacity = c->capacity -
334                 bch2_fs_usage_read_one(c, &c->usage_base->hidden);
335
336         data            = bch2_fs_usage_read_one(c, &c->usage_base->data) +
337                 bch2_fs_usage_read_one(c, &c->usage_base->btree);
338         reserved        = bch2_fs_usage_read_one(c, &c->usage_base->reserved) +
339                 bch2_fs_usage_read_one(c, &c->usage_base->online_reserved);
340
341         ret.used        = min(ret.capacity, data + reserve_factor(reserved));
342         ret.free        = ret.capacity - ret.used;
343
344         ret.nr_inodes   = bch2_fs_usage_read_one(c, &c->usage_base->nr_inodes);
345
346         return ret;
347 }
348
349 struct bch_fs_usage_short
350 bch2_fs_usage_read_short(struct bch_fs *c)
351 {
352         struct bch_fs_usage_short ret;
353
354         percpu_down_read(&c->mark_lock);
355         ret = __bch2_fs_usage_read_short(c);
356         percpu_up_read(&c->mark_lock);
357
358         return ret;
359 }
360
361 static inline int is_unavailable_bucket(struct bucket_mark m)
362 {
363         return !is_available_bucket(m);
364 }
365
366 static inline int is_fragmented_bucket(struct bucket_mark m,
367                                        struct bch_dev *ca)
368 {
369         if (!m.owned_by_allocator &&
370             m.data_type == BCH_DATA_USER &&
371             bucket_sectors_used(m))
372                 return max_t(int, 0, (int) ca->mi.bucket_size -
373                              bucket_sectors_used(m));
374         return 0;
375 }
376
377 static inline enum bch_data_type bucket_type(struct bucket_mark m)
378 {
379         return m.cached_sectors && !m.dirty_sectors
380                 ? BCH_DATA_CACHED
381                 : m.data_type;
382 }
383
384 static bool bucket_became_unavailable(struct bucket_mark old,
385                                       struct bucket_mark new)
386 {
387         return is_available_bucket(old) &&
388                !is_available_bucket(new);
389 }
390
391 int bch2_fs_usage_apply(struct bch_fs *c,
392                         struct bch_fs_usage *fs_usage,
393                         struct disk_reservation *disk_res,
394                         unsigned journal_seq)
395 {
396         s64 added = fs_usage->data + fs_usage->reserved;
397         s64 should_not_have_added;
398         int ret = 0;
399
400         percpu_rwsem_assert_held(&c->mark_lock);
401
402         /*
403          * Not allowed to reduce sectors_available except by getting a
404          * reservation:
405          */
406         should_not_have_added = added - (s64) (disk_res ? disk_res->sectors : 0);
407         if (WARN_ONCE(should_not_have_added > 0,
408                       "disk usage increased by %lli without a reservation",
409                       should_not_have_added)) {
410                 atomic64_sub(should_not_have_added, &c->sectors_available);
411                 added -= should_not_have_added;
412                 ret = -1;
413         }
414
415         if (added > 0) {
416                 disk_res->sectors               -= added;
417                 fs_usage->online_reserved       -= added;
418         }
419
420         preempt_disable();
421         acc_u64s((u64 *) fs_usage_ptr(c, journal_seq, false),
422                  (u64 *) fs_usage, fs_usage_u64s(c));
423         preempt_enable();
424
425         return ret;
426 }
427
428 static inline void account_bucket(struct bch_fs_usage *fs_usage,
429                                   struct bch_dev_usage *dev_usage,
430                                   enum bch_data_type type,
431                                   int nr, s64 size)
432 {
433         if (type == BCH_DATA_SB || type == BCH_DATA_JOURNAL)
434                 fs_usage->hidden        += size;
435
436         dev_usage->buckets[type]        += nr;
437 }
438
439 static void bch2_dev_usage_update(struct bch_fs *c, struct bch_dev *ca,
440                                   struct bch_fs_usage *fs_usage,
441                                   struct bucket_mark old, struct bucket_mark new,
442                                   bool gc)
443 {
444         struct bch_dev_usage *dev_usage;
445
446         percpu_rwsem_assert_held(&c->mark_lock);
447
448         preempt_disable();
449         dev_usage = this_cpu_ptr(ca->usage[gc]);
450
451         if (bucket_type(old))
452                 account_bucket(fs_usage, dev_usage, bucket_type(old),
453                                -1, -ca->mi.bucket_size);
454
455         if (bucket_type(new))
456                 account_bucket(fs_usage, dev_usage, bucket_type(new),
457                                1, ca->mi.bucket_size);
458
459         dev_usage->buckets_alloc +=
460                 (int) new.owned_by_allocator - (int) old.owned_by_allocator;
461         dev_usage->buckets_ec +=
462                 (int) new.stripe - (int) old.stripe;
463         dev_usage->buckets_unavailable +=
464                 is_unavailable_bucket(new) - is_unavailable_bucket(old);
465
466         dev_usage->sectors[old.data_type] -= old.dirty_sectors;
467         dev_usage->sectors[new.data_type] += new.dirty_sectors;
468         dev_usage->sectors[BCH_DATA_CACHED] +=
469                 (int) new.cached_sectors - (int) old.cached_sectors;
470         dev_usage->sectors_fragmented +=
471                 is_fragmented_bucket(new, ca) - is_fragmented_bucket(old, ca);
472         preempt_enable();
473
474         if (!is_available_bucket(old) && is_available_bucket(new))
475                 bch2_wake_allocator(ca);
476 }
477
478 void bch2_dev_usage_from_buckets(struct bch_fs *c)
479 {
480         struct bch_dev *ca;
481         struct bucket_mark old = { .v.counter = 0 };
482         struct bucket_array *buckets;
483         struct bucket *g;
484         unsigned i;
485         int cpu;
486
487         c->usage_base->hidden = 0;
488
489         for_each_member_device(ca, c, i) {
490                 for_each_possible_cpu(cpu)
491                         memset(per_cpu_ptr(ca->usage[0], cpu), 0,
492                                sizeof(*ca->usage[0]));
493
494                 buckets = bucket_array(ca);
495
496                 for_each_bucket(g, buckets)
497                         bch2_dev_usage_update(c, ca, c->usage_base,
498                                               old, g->mark, false);
499         }
500 }
501
502 static inline int update_replicas(struct bch_fs *c,
503                                   struct bch_fs_usage *fs_usage,
504                                   struct bch_replicas_entry *r,
505                                   s64 sectors)
506 {
507         int idx = bch2_replicas_entry_idx(c, r);
508
509         if (idx < 0)
510                 return -1;
511
512         if (!fs_usage)
513                 return 0;
514
515         switch (r->data_type) {
516         case BCH_DATA_BTREE:
517                 fs_usage->btree         += sectors;
518                 break;
519         case BCH_DATA_USER:
520                 fs_usage->data          += sectors;
521                 break;
522         case BCH_DATA_CACHED:
523                 fs_usage->cached        += sectors;
524                 break;
525         }
526         fs_usage->replicas[idx]         += sectors;
527         return 0;
528 }
529
530 static inline void update_cached_sectors(struct bch_fs *c,
531                                          struct bch_fs_usage *fs_usage,
532                                          unsigned dev, s64 sectors)
533 {
534         struct bch_replicas_padded r;
535
536         bch2_replicas_entry_cached(&r.e, dev);
537
538         update_replicas(c, fs_usage, &r.e, sectors);
539 }
540
541 static struct replicas_delta_list *
542 replicas_deltas_realloc(struct btree_trans *trans, unsigned more)
543 {
544         struct replicas_delta_list *d = trans->fs_usage_deltas;
545         unsigned new_size = d ? (d->size + more) * 2 : 128;
546
547         if (!d || d->used + more > d->size) {
548                 d = krealloc(d, sizeof(*d) + new_size, GFP_NOIO|__GFP_ZERO);
549                 BUG_ON(!d);
550
551                 d->size = new_size;
552                 trans->fs_usage_deltas = d;
553         }
554         return d;
555 }
556
557 static inline void update_replicas_list(struct btree_trans *trans,
558                                         struct bch_replicas_entry *r,
559                                         s64 sectors)
560 {
561         struct replicas_delta_list *d;
562         struct replicas_delta *n;
563         unsigned b;
564
565         if (!sectors)
566                 return;
567
568         b = replicas_entry_bytes(r) + 8;
569         d = replicas_deltas_realloc(trans, b);
570
571         n = (void *) d->d + d->used;
572         n->delta = sectors;
573         memcpy(&n->r, r, replicas_entry_bytes(r));
574         d->used += b;
575 }
576
577 static inline void update_cached_sectors_list(struct btree_trans *trans,
578                                               unsigned dev, s64 sectors)
579 {
580         struct bch_replicas_padded r;
581
582         bch2_replicas_entry_cached(&r.e, dev);
583
584         update_replicas_list(trans, &r.e, sectors);
585 }
586
587 static inline struct replicas_delta *
588 replicas_delta_next(struct replicas_delta *d)
589 {
590         return (void *) d + replicas_entry_bytes(&d->r) + 8;
591 }
592
593 int bch2_replicas_delta_list_apply(struct bch_fs *c,
594                                    struct bch_fs_usage *fs_usage,
595                                    struct replicas_delta_list *r)
596 {
597         struct replicas_delta *d = r->d;
598         struct replicas_delta *top = (void *) r->d + r->used;
599         unsigned i;
600
601         for (d = r->d; d != top; d = replicas_delta_next(d))
602                 if (update_replicas(c, fs_usage, &d->r, d->delta)) {
603                         top = d;
604                         goto unwind;
605                 }
606
607         if (!fs_usage)
608                 return 0;
609
610         fs_usage->nr_inodes += r->nr_inodes;
611
612         for (i = 0; i < BCH_REPLICAS_MAX; i++) {
613                 fs_usage->reserved += r->persistent_reserved[i];
614                 fs_usage->persistent_reserved[i] += r->persistent_reserved[i];
615         }
616
617         return 0;
618 unwind:
619         for (d = r->d; d != top; d = replicas_delta_next(d))
620                 update_replicas(c, fs_usage, &d->r, -d->delta);
621         return -1;
622 }
623
624 #define do_mark_fn(fn, c, pos, flags, ...)                              \
625 ({                                                                      \
626         int gc, ret = 0;                                                \
627                                                                         \
628         percpu_rwsem_assert_held(&c->mark_lock);                        \
629                                                                         \
630         for (gc = 0; gc < 2 && !ret; gc++)                              \
631                 if (!gc == !(flags & BTREE_TRIGGER_GC) ||               \
632                     (gc && gc_visited(c, pos)))                         \
633                         ret = fn(c, __VA_ARGS__, gc);                   \
634         ret;                                                            \
635 })
636
637 static int __bch2_invalidate_bucket(struct bch_fs *c, struct bch_dev *ca,
638                                     size_t b, struct bucket_mark *ret,
639                                     bool gc)
640 {
641         struct bch_fs_usage *fs_usage = fs_usage_ptr(c, 0, gc);
642         struct bucket *g = __bucket(ca, b, gc);
643         struct bucket_mark old, new;
644
645         old = bucket_cmpxchg(g, new, ({
646                 BUG_ON(!is_available_bucket(new));
647
648                 new.owned_by_allocator  = true;
649                 new.data_type           = 0;
650                 new.cached_sectors      = 0;
651                 new.dirty_sectors       = 0;
652                 new.gen++;
653         }));
654
655         bch2_dev_usage_update(c, ca, fs_usage, old, new, gc);
656
657         if (old.cached_sectors)
658                 update_cached_sectors(c, fs_usage, ca->dev_idx,
659                                       -((s64) old.cached_sectors));
660
661         if (!gc)
662                 *ret = old;
663         return 0;
664 }
665
666 void bch2_invalidate_bucket(struct bch_fs *c, struct bch_dev *ca,
667                             size_t b, struct bucket_mark *old)
668 {
669         do_mark_fn(__bch2_invalidate_bucket, c, gc_phase(GC_PHASE_START), 0,
670                    ca, b, old);
671
672         if (!old->owned_by_allocator && old->cached_sectors)
673                 trace_invalidate(ca, bucket_to_sector(ca, b),
674                                  old->cached_sectors);
675 }
676
677 static int __bch2_mark_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
678                                     size_t b, bool owned_by_allocator,
679                                     bool gc)
680 {
681         struct bch_fs_usage *fs_usage = fs_usage_ptr(c, 0, gc);
682         struct bucket *g = __bucket(ca, b, gc);
683         struct bucket_mark old, new;
684
685         old = bucket_cmpxchg(g, new, ({
686                 new.owned_by_allocator  = owned_by_allocator;
687         }));
688
689         bch2_dev_usage_update(c, ca, fs_usage, old, new, gc);
690
691         BUG_ON(!gc &&
692                !owned_by_allocator && !old.owned_by_allocator);
693
694         return 0;
695 }
696
697 void bch2_mark_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
698                             size_t b, bool owned_by_allocator,
699                             struct gc_pos pos, unsigned flags)
700 {
701         preempt_disable();
702
703         do_mark_fn(__bch2_mark_alloc_bucket, c, pos, flags,
704                    ca, b, owned_by_allocator);
705
706         preempt_enable();
707 }
708
709 static int bch2_mark_alloc(struct bch_fs *c, struct bkey_s_c k,
710                            struct bch_fs_usage *fs_usage,
711                            u64 journal_seq, unsigned flags)
712 {
713         bool gc = flags & BTREE_TRIGGER_GC;
714         struct bkey_alloc_unpacked u;
715         struct bch_dev *ca;
716         struct bucket *g;
717         struct bucket_mark old, m;
718
719         /*
720          * alloc btree is read in by bch2_alloc_read, not gc:
721          */
722         if ((flags & BTREE_TRIGGER_GC) &&
723             !(flags & BTREE_TRIGGER_BUCKET_INVALIDATE))
724                 return 0;
725
726         ca = bch_dev_bkey_exists(c, k.k->p.inode);
727
728         if (k.k->p.offset >= ca->mi.nbuckets)
729                 return 0;
730
731         g = __bucket(ca, k.k->p.offset, gc);
732         u = bch2_alloc_unpack(k);
733
734         old = bucket_cmpxchg(g, m, ({
735                 m.gen                   = u.gen;
736                 m.data_type             = u.data_type;
737                 m.dirty_sectors         = u.dirty_sectors;
738                 m.cached_sectors        = u.cached_sectors;
739
740                 if (journal_seq) {
741                         m.journal_seq_valid     = 1;
742                         m.journal_seq           = journal_seq;
743                 }
744         }));
745
746         if (!(flags & BTREE_TRIGGER_ALLOC_READ))
747                 bch2_dev_usage_update(c, ca, fs_usage, old, m, gc);
748
749         g->io_time[READ]        = u.read_time;
750         g->io_time[WRITE]       = u.write_time;
751         g->oldest_gen           = u.oldest_gen;
752         g->gen_valid            = 1;
753
754         /*
755          * need to know if we're getting called from the invalidate path or
756          * not:
757          */
758
759         if ((flags & BTREE_TRIGGER_BUCKET_INVALIDATE) &&
760             old.cached_sectors) {
761                 update_cached_sectors(c, fs_usage, ca->dev_idx,
762                                       -old.cached_sectors);
763                 trace_invalidate(ca, bucket_to_sector(ca, k.k->p.offset),
764                                  old.cached_sectors);
765         }
766
767         return 0;
768 }
769
770 #define checked_add(a, b)                                       \
771 ({                                                              \
772         unsigned _res = (unsigned) (a) + (b);                   \
773         bool overflow = _res > U16_MAX;                         \
774         if (overflow)                                           \
775                 _res = U16_MAX;                                 \
776         (a) = _res;                                             \
777         overflow;                                               \
778 })
779
780 static int __bch2_mark_metadata_bucket(struct bch_fs *c, struct bch_dev *ca,
781                                        size_t b, enum bch_data_type type,
782                                        unsigned sectors, bool gc)
783 {
784         struct bucket *g = __bucket(ca, b, gc);
785         struct bucket_mark old, new;
786         bool overflow;
787
788         BUG_ON(type != BCH_DATA_SB &&
789                type != BCH_DATA_JOURNAL);
790
791         old = bucket_cmpxchg(g, new, ({
792                 new.data_type   = type;
793                 overflow = checked_add(new.dirty_sectors, sectors);
794         }));
795
796         bch2_fs_inconsistent_on(old.data_type &&
797                                 old.data_type != type, c,
798                 "different types of data in same bucket: %s, %s",
799                 bch2_data_types[old.data_type],
800                 bch2_data_types[type]);
801
802         bch2_fs_inconsistent_on(overflow, c,
803                 "bucket sector count overflow: %u + %u > U16_MAX",
804                 old.dirty_sectors, sectors);
805
806         if (c)
807                 bch2_dev_usage_update(c, ca, fs_usage_ptr(c, 0, gc),
808                                       old, new, gc);
809
810         return 0;
811 }
812
813 void bch2_mark_metadata_bucket(struct bch_fs *c, struct bch_dev *ca,
814                                size_t b, enum bch_data_type type,
815                                unsigned sectors, struct gc_pos pos,
816                                unsigned flags)
817 {
818         BUG_ON(type != BCH_DATA_SB &&
819                type != BCH_DATA_JOURNAL);
820
821         preempt_disable();
822
823         if (likely(c)) {
824                 do_mark_fn(__bch2_mark_metadata_bucket, c, pos, flags,
825                            ca, b, type, sectors);
826         } else {
827                 __bch2_mark_metadata_bucket(c, ca, b, type, sectors, 0);
828         }
829
830         preempt_enable();
831 }
832
833 static s64 disk_sectors_scaled(unsigned n, unsigned d, unsigned sectors)
834 {
835         return DIV_ROUND_UP(sectors * n, d);
836 }
837
838 static s64 __ptr_disk_sectors_delta(unsigned old_size,
839                                     unsigned offset, s64 delta,
840                                     unsigned flags,
841                                     unsigned n, unsigned d)
842 {
843         BUG_ON(!n || !d);
844
845         if (flags & BTREE_TRIGGER_OVERWRITE_SPLIT) {
846                 BUG_ON(offset + -delta > old_size);
847
848                 return -disk_sectors_scaled(n, d, old_size) +
849                         disk_sectors_scaled(n, d, offset) +
850                         disk_sectors_scaled(n, d, old_size - offset + delta);
851         } else if (flags & BTREE_TRIGGER_OVERWRITE) {
852                 BUG_ON(offset + -delta > old_size);
853
854                 return -disk_sectors_scaled(n, d, old_size) +
855                         disk_sectors_scaled(n, d, old_size + delta);
856         } else {
857                 return  disk_sectors_scaled(n, d, delta);
858         }
859 }
860
861 static s64 ptr_disk_sectors_delta(struct extent_ptr_decoded p,
862                                   unsigned offset, s64 delta,
863                                   unsigned flags)
864 {
865         return __ptr_disk_sectors_delta(p.crc.live_size,
866                                         offset, delta, flags,
867                                         p.crc.compressed_size,
868                                         p.crc.uncompressed_size);
869 }
870
871 static void bucket_set_stripe(struct bch_fs *c,
872                               const struct bch_stripe *v,
873                               struct bch_fs_usage *fs_usage,
874                               u64 journal_seq,
875                               unsigned flags)
876 {
877         bool enabled = !(flags & BTREE_TRIGGER_OVERWRITE);
878         bool gc = flags & BTREE_TRIGGER_GC;
879         unsigned i;
880
881         for (i = 0; i < v->nr_blocks; i++) {
882                 const struct bch_extent_ptr *ptr = v->ptrs + i;
883                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
884                 struct bucket *g = PTR_BUCKET(ca, ptr, gc);
885                 struct bucket_mark new, old;
886
887                 old = bucket_cmpxchg(g, new, ({
888                         new.stripe                      = enabled;
889                         if (journal_seq) {
890                                 new.journal_seq_valid   = 1;
891                                 new.journal_seq         = journal_seq;
892                         }
893                 }));
894
895                 bch2_dev_usage_update(c, ca, fs_usage, old, new, gc);
896
897                 /*
898                  * XXX write repair code for these, flag stripe as possibly bad
899                  */
900                 if (old.gen != ptr->gen)
901                         bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
902                                       "stripe with stale pointer");
903 #if 0
904                 /*
905                  * We'd like to check for these, but these checks don't work
906                  * yet:
907                  */
908                 if (old.stripe && enabled)
909                         bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
910                                       "multiple stripes using same bucket");
911
912                 if (!old.stripe && !enabled)
913                         bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
914                                       "deleting stripe but bucket not marked as stripe bucket");
915 #endif
916         }
917 }
918
919 static bool bch2_mark_pointer(struct bch_fs *c,
920                               struct extent_ptr_decoded p,
921                               s64 sectors, enum bch_data_type data_type,
922                               struct bch_fs_usage *fs_usage,
923                               u64 journal_seq, unsigned flags)
924 {
925         bool gc = flags & BTREE_TRIGGER_GC;
926         struct bucket_mark old, new;
927         struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
928         struct bucket *g = PTR_BUCKET(ca, &p.ptr, gc);
929         bool overflow;
930         u64 v;
931
932         v = atomic64_read(&g->_mark.v);
933         do {
934                 new.v.counter = old.v.counter = v;
935
936                 /*
937                  * Check this after reading bucket mark to guard against
938                  * the allocator invalidating a bucket after we've already
939                  * checked the gen
940                  */
941                 if (gen_after(p.ptr.gen, new.gen)) {
942                         bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
943                                       "pointer gen in the future");
944                         return true;
945                 }
946
947                 if (new.gen != p.ptr.gen) {
948                         /* XXX write repair code for this */
949                         if (!p.ptr.cached &&
950                             test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))
951                                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
952                                               "stale dirty pointer");
953                         return true;
954                 }
955
956                 if (!p.ptr.cached)
957                         overflow = checked_add(new.dirty_sectors, sectors);
958                 else
959                         overflow = checked_add(new.cached_sectors, sectors);
960
961                 if (!new.dirty_sectors &&
962                     !new.cached_sectors) {
963                         new.data_type   = 0;
964
965                         if (journal_seq) {
966                                 new.journal_seq_valid = 1;
967                                 new.journal_seq = journal_seq;
968                         }
969                 } else {
970                         new.data_type = data_type;
971                 }
972
973                 if (flags & BTREE_TRIGGER_NOATOMIC) {
974                         g->_mark = new;
975                         break;
976                 }
977         } while ((v = atomic64_cmpxchg(&g->_mark.v,
978                               old.v.counter,
979                               new.v.counter)) != old.v.counter);
980
981         if (old.data_type && old.data_type != data_type)
982                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
983                         "bucket %u:%zu gen %u different types of data in same bucket: %s, %s",
984                         p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr),
985                         new.gen,
986                         bch2_data_types[old.data_type],
987                         bch2_data_types[data_type]);
988
989         bch2_fs_inconsistent_on(overflow, c,
990                 "bucket sector count overflow: %u + %lli > U16_MAX",
991                 !p.ptr.cached
992                 ? old.dirty_sectors
993                 : old.cached_sectors, sectors);
994
995         bch2_dev_usage_update(c, ca, fs_usage, old, new, gc);
996
997         BUG_ON(!gc && bucket_became_unavailable(old, new));
998
999         return false;
1000 }
1001
1002 static int bch2_mark_stripe_ptr(struct bch_fs *c,
1003                                 struct bch_extent_stripe_ptr p,
1004                                 enum bch_data_type data_type,
1005                                 struct bch_fs_usage *fs_usage,
1006                                 s64 sectors, unsigned flags,
1007                                 struct bch_replicas_padded *r,
1008                                 unsigned *nr_data,
1009                                 unsigned *nr_parity)
1010 {
1011         bool gc = flags & BTREE_TRIGGER_GC;
1012         struct stripe *m;
1013         unsigned old, new;
1014         int blocks_nonempty_delta;
1015
1016         m = genradix_ptr(&c->stripes[gc], p.idx);
1017
1018         spin_lock(&c->ec_stripes_heap_lock);
1019
1020         if (!m || !m->alive) {
1021                 spin_unlock(&c->ec_stripes_heap_lock);
1022                 bch_err_ratelimited(c, "pointer to nonexistent stripe %llu",
1023                                     (u64) p.idx);
1024                 return -EIO;
1025         }
1026
1027         BUG_ON(m->r.e.data_type != data_type);
1028
1029         *nr_data        = m->nr_blocks - m->nr_redundant;
1030         *nr_parity      = m->nr_redundant;
1031         *r = m->r;
1032
1033         old = m->block_sectors[p.block];
1034         m->block_sectors[p.block] += sectors;
1035         new = m->block_sectors[p.block];
1036
1037         blocks_nonempty_delta = (int) !!new - (int) !!old;
1038         if (blocks_nonempty_delta) {
1039                 m->blocks_nonempty += blocks_nonempty_delta;
1040
1041                 if (!gc)
1042                         bch2_stripes_heap_update(c, m, p.idx);
1043         }
1044
1045         m->dirty = true;
1046
1047         spin_unlock(&c->ec_stripes_heap_lock);
1048
1049         return 0;
1050 }
1051
1052 static int bch2_mark_extent(struct bch_fs *c, struct bkey_s_c k,
1053                             unsigned offset, s64 sectors,
1054                             enum bch_data_type data_type,
1055                             struct bch_fs_usage *fs_usage,
1056                             unsigned journal_seq, unsigned flags)
1057 {
1058         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1059         const union bch_extent_entry *entry;
1060         struct extent_ptr_decoded p;
1061         struct bch_replicas_padded r;
1062         s64 dirty_sectors = 0;
1063         int ret;
1064
1065         r.e.data_type   = data_type;
1066         r.e.nr_devs     = 0;
1067         r.e.nr_required = 1;
1068
1069         BUG_ON(!sectors);
1070
1071         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
1072                 s64 disk_sectors = data_type == BCH_DATA_BTREE
1073                         ? sectors
1074                         : ptr_disk_sectors_delta(p, offset, sectors, flags);
1075                 bool stale = bch2_mark_pointer(c, p, disk_sectors, data_type,
1076                                                fs_usage, journal_seq, flags);
1077
1078                 if (p.ptr.cached) {
1079                         if (!stale)
1080                                 update_cached_sectors(c, fs_usage, p.ptr.dev,
1081                                                       disk_sectors);
1082                 } else if (!p.has_ec) {
1083                         dirty_sectors          += disk_sectors;
1084                         r.e.devs[r.e.nr_devs++] = p.ptr.dev;
1085                 } else {
1086                         struct bch_replicas_padded ec_r;
1087                         unsigned nr_data, nr_parity;
1088                         s64 parity_sectors;
1089
1090                         ret = bch2_mark_stripe_ptr(c, p.ec, data_type,
1091                                         fs_usage, disk_sectors, flags,
1092                                         &ec_r, &nr_data, &nr_parity);
1093                         if (ret)
1094                                 return ret;
1095
1096                         parity_sectors =
1097                                 __ptr_disk_sectors_delta(p.crc.live_size,
1098                                         offset, sectors, flags,
1099                                         p.crc.compressed_size * nr_parity,
1100                                         p.crc.uncompressed_size * nr_data);
1101
1102                         update_replicas(c, fs_usage, &ec_r.e,
1103                                         disk_sectors + parity_sectors);
1104
1105                         /*
1106                          * There may be other dirty pointers in this extent, but
1107                          * if so they're not required for mounting if we have an
1108                          * erasure coded pointer in this extent:
1109                          */
1110                         r.e.nr_required = 0;
1111                 }
1112         }
1113
1114         if (r.e.nr_devs)
1115                 update_replicas(c, fs_usage, &r.e, dirty_sectors);
1116
1117         return 0;
1118 }
1119
1120 static int bch2_mark_stripe(struct bch_fs *c, struct bkey_s_c k,
1121                             struct bch_fs_usage *fs_usage,
1122                             u64 journal_seq, unsigned flags)
1123 {
1124         bool gc = flags & BTREE_TRIGGER_GC;
1125         struct bkey_s_c_stripe s = bkey_s_c_to_stripe(k);
1126         size_t idx = s.k->p.offset;
1127         struct stripe *m = genradix_ptr(&c->stripes[gc], idx);
1128         unsigned i;
1129
1130         spin_lock(&c->ec_stripes_heap_lock);
1131
1132         if (!m || ((flags & BTREE_TRIGGER_OVERWRITE) && !m->alive)) {
1133                 spin_unlock(&c->ec_stripes_heap_lock);
1134                 bch_err_ratelimited(c, "error marking nonexistent stripe %zu",
1135                                     idx);
1136                 return -1;
1137         }
1138
1139         if (!(flags & BTREE_TRIGGER_OVERWRITE)) {
1140                 m->sectors      = le16_to_cpu(s.v->sectors);
1141                 m->algorithm    = s.v->algorithm;
1142                 m->nr_blocks    = s.v->nr_blocks;
1143                 m->nr_redundant = s.v->nr_redundant;
1144
1145                 bch2_bkey_to_replicas(&m->r.e, k);
1146
1147                 /*
1148                  * XXX: account for stripes somehow here
1149                  */
1150 #if 0
1151                 update_replicas(c, fs_usage, &m->r.e, stripe_sectors);
1152 #endif
1153
1154                 /* gc recalculates these fields: */
1155                 if (!(flags & BTREE_TRIGGER_GC)) {
1156                         for (i = 0; i < s.v->nr_blocks; i++) {
1157                                 m->block_sectors[i] =
1158                                         stripe_blockcount_get(s.v, i);
1159                                 m->blocks_nonempty += !!m->block_sectors[i];
1160                         }
1161                 }
1162
1163                 if (!gc)
1164                         bch2_stripes_heap_update(c, m, idx);
1165                 m->alive        = true;
1166         } else {
1167                 if (!gc)
1168                         bch2_stripes_heap_del(c, m, idx);
1169                 memset(m, 0, sizeof(*m));
1170         }
1171
1172         spin_unlock(&c->ec_stripes_heap_lock);
1173
1174         bucket_set_stripe(c, s.v, fs_usage, 0, flags);
1175         return 0;
1176 }
1177
1178 int bch2_mark_key_locked(struct bch_fs *c,
1179                    struct bkey_s_c k,
1180                    unsigned offset, s64 sectors,
1181                    struct bch_fs_usage *fs_usage,
1182                    u64 journal_seq, unsigned flags)
1183 {
1184         int ret = 0;
1185
1186         preempt_disable();
1187
1188         if (!fs_usage || (flags & BTREE_TRIGGER_GC))
1189                 fs_usage = fs_usage_ptr(c, journal_seq,
1190                                         flags & BTREE_TRIGGER_GC);
1191
1192         switch (k.k->type) {
1193         case KEY_TYPE_alloc:
1194                 ret = bch2_mark_alloc(c, k, fs_usage, journal_seq, flags);
1195                 break;
1196         case KEY_TYPE_btree_ptr:
1197         case KEY_TYPE_btree_ptr_v2:
1198                 sectors = !(flags & BTREE_TRIGGER_OVERWRITE)
1199                         ?  c->opts.btree_node_size
1200                         : -c->opts.btree_node_size;
1201
1202                 ret = bch2_mark_extent(c, k, offset, sectors, BCH_DATA_BTREE,
1203                                 fs_usage, journal_seq, flags);
1204                 break;
1205         case KEY_TYPE_extent:
1206         case KEY_TYPE_reflink_v:
1207                 ret = bch2_mark_extent(c, k, offset, sectors, BCH_DATA_USER,
1208                                 fs_usage, journal_seq, flags);
1209                 break;
1210         case KEY_TYPE_stripe:
1211                 ret = bch2_mark_stripe(c, k, fs_usage, journal_seq, flags);
1212                 break;
1213         case KEY_TYPE_inode:
1214                 if (!(flags & BTREE_TRIGGER_OVERWRITE))
1215                         fs_usage->nr_inodes++;
1216                 else
1217                         fs_usage->nr_inodes--;
1218                 break;
1219         case KEY_TYPE_reservation: {
1220                 unsigned replicas = bkey_s_c_to_reservation(k).v->nr_replicas;
1221
1222                 sectors *= replicas;
1223                 replicas = clamp_t(unsigned, replicas, 1,
1224                                    ARRAY_SIZE(fs_usage->persistent_reserved));
1225
1226                 fs_usage->reserved                              += sectors;
1227                 fs_usage->persistent_reserved[replicas - 1]     += sectors;
1228                 break;
1229         }
1230         }
1231
1232         preempt_enable();
1233
1234         return ret;
1235 }
1236
1237 int bch2_mark_key(struct bch_fs *c, struct bkey_s_c k,
1238                   unsigned offset, s64 sectors,
1239                   struct bch_fs_usage *fs_usage,
1240                   u64 journal_seq, unsigned flags)
1241 {
1242         int ret;
1243
1244         percpu_down_read(&c->mark_lock);
1245         ret = bch2_mark_key_locked(c, k, offset, sectors,
1246                                    fs_usage, journal_seq, flags);
1247         percpu_up_read(&c->mark_lock);
1248
1249         return ret;
1250 }
1251
1252 inline int bch2_mark_overwrite(struct btree_trans *trans,
1253                                struct btree_iter *iter,
1254                                struct bkey_s_c old,
1255                                struct bkey_i *new,
1256                                struct bch_fs_usage *fs_usage,
1257                                unsigned flags,
1258                                bool is_extents)
1259 {
1260         struct bch_fs           *c = trans->c;
1261         unsigned                offset = 0;
1262         s64                     sectors = -((s64) old.k->size);
1263
1264         flags |= BTREE_TRIGGER_OVERWRITE;
1265
1266         if (is_extents
1267             ? bkey_cmp(new->k.p, bkey_start_pos(old.k)) <= 0
1268             : bkey_cmp(new->k.p, old.k->p))
1269                 return 0;
1270
1271         if (is_extents) {
1272                 switch (bch2_extent_overlap(&new->k, old.k)) {
1273                 case BCH_EXTENT_OVERLAP_ALL:
1274                         offset = 0;
1275                         sectors = -((s64) old.k->size);
1276                         break;
1277                 case BCH_EXTENT_OVERLAP_BACK:
1278                         offset = bkey_start_offset(&new->k) -
1279                                 bkey_start_offset(old.k);
1280                         sectors = bkey_start_offset(&new->k) -
1281                                 old.k->p.offset;
1282                         break;
1283                 case BCH_EXTENT_OVERLAP_FRONT:
1284                         offset = 0;
1285                         sectors = bkey_start_offset(old.k) -
1286                                 new->k.p.offset;
1287                         break;
1288                 case BCH_EXTENT_OVERLAP_MIDDLE:
1289                         offset = bkey_start_offset(&new->k) -
1290                                 bkey_start_offset(old.k);
1291                         sectors = -((s64) new->k.size);
1292                         flags |= BTREE_TRIGGER_OVERWRITE_SPLIT;
1293                         break;
1294                 }
1295
1296                 BUG_ON(sectors >= 0);
1297         }
1298
1299         return bch2_mark_key_locked(c, old, offset, sectors, fs_usage,
1300                                     trans->journal_res.seq, flags) ?: 1;
1301 }
1302
1303 int bch2_mark_update(struct btree_trans *trans,
1304                      struct btree_iter *iter,
1305                      struct bkey_i *insert,
1306                      struct bch_fs_usage *fs_usage,
1307                      unsigned flags)
1308 {
1309         struct bch_fs           *c = trans->c;
1310         struct btree            *b = iter->l[0].b;
1311         struct btree_node_iter  node_iter = iter->l[0].iter;
1312         struct bkey_packed      *_k;
1313         int ret = 0;
1314
1315         if (unlikely(flags & BTREE_TRIGGER_NORUN))
1316                 return 0;
1317
1318         if (!btree_node_type_needs_gc(iter->btree_id))
1319                 return 0;
1320
1321         bch2_mark_key_locked(c, bkey_i_to_s_c(insert),
1322                 0, insert->k.size,
1323                 fs_usage, trans->journal_res.seq,
1324                 BTREE_TRIGGER_INSERT|flags);
1325
1326         if (unlikely(flags & BTREE_TRIGGER_NOOVERWRITES))
1327                 return 0;
1328
1329         /*
1330          * For non extents, we only mark the new key, not the key being
1331          * overwritten - unless we're actually deleting:
1332          */
1333         if ((iter->btree_id == BTREE_ID_ALLOC ||
1334              iter->btree_id == BTREE_ID_EC) &&
1335             !bkey_deleted(&insert->k))
1336                 return 0;
1337
1338         while ((_k = bch2_btree_node_iter_peek(&node_iter, b))) {
1339                 struct bkey             unpacked;
1340                 struct bkey_s_c         k = bkey_disassemble(b, _k, &unpacked);
1341
1342                 ret = bch2_mark_overwrite(trans, iter, k, insert,
1343                                           fs_usage, flags,
1344                                           btree_node_type_is_extents(iter->btree_id));
1345                 if (ret <= 0)
1346                         break;
1347
1348                 bch2_btree_node_iter_advance(&node_iter, b);
1349         }
1350
1351         return ret;
1352 }
1353
1354 void bch2_trans_fs_usage_apply(struct btree_trans *trans,
1355                                struct bch_fs_usage *fs_usage)
1356 {
1357         struct bch_fs *c = trans->c;
1358         struct btree_insert_entry *i;
1359         static int warned_disk_usage = 0;
1360         u64 disk_res_sectors = trans->disk_res ? trans->disk_res->sectors : 0;
1361         char buf[200];
1362
1363         if (!bch2_fs_usage_apply(c, fs_usage, trans->disk_res,
1364                                  trans->journal_res.seq) ||
1365             warned_disk_usage ||
1366             xchg(&warned_disk_usage, 1))
1367                 return;
1368
1369         bch_err(c, "disk usage increased more than %llu sectors reserved",
1370                 disk_res_sectors);
1371
1372         trans_for_each_update(trans, i) {
1373                 struct btree_iter       *iter = i->iter;
1374                 struct btree            *b = iter->l[0].b;
1375                 struct btree_node_iter  node_iter = iter->l[0].iter;
1376                 struct bkey_packed      *_k;
1377
1378                 pr_err("while inserting");
1379                 bch2_bkey_val_to_text(&PBUF(buf), c, bkey_i_to_s_c(i->k));
1380                 pr_err("%s", buf);
1381                 pr_err("overlapping with");
1382
1383                 node_iter = iter->l[0].iter;
1384                 while ((_k = bch2_btree_node_iter_peek(&node_iter, b))) {
1385                         struct bkey             unpacked;
1386                         struct bkey_s_c         k;
1387
1388                         k = bkey_disassemble(b, _k, &unpacked);
1389
1390                         if (btree_node_is_extents(b)
1391                             ? bkey_cmp(i->k->k.p, bkey_start_pos(k.k)) <= 0
1392                             : bkey_cmp(i->k->k.p, k.k->p))
1393                                 break;
1394
1395                         bch2_bkey_val_to_text(&PBUF(buf), c, k);
1396                         pr_err("%s", buf);
1397
1398                         bch2_btree_node_iter_advance(&node_iter, b);
1399                 }
1400         }
1401 }
1402
1403 /* trans_mark: */
1404
1405 static int trans_get_key(struct btree_trans *trans,
1406                          enum btree_id btree_id, struct bpos pos,
1407                          struct btree_iter **iter,
1408                          struct bkey_s_c *k)
1409 {
1410         struct btree_insert_entry *i;
1411         int ret;
1412
1413         trans_for_each_update(trans, i)
1414                 if (i->iter->btree_id == btree_id &&
1415                     (btree_node_type_is_extents(btree_id)
1416                      ? bkey_cmp(pos, bkey_start_pos(&i->k->k)) >= 0 &&
1417                        bkey_cmp(pos, i->k->k.p) < 0
1418                      : !bkey_cmp(pos, i->iter->pos))) {
1419                         *iter   = i->iter;
1420                         *k      = bkey_i_to_s_c(i->k);
1421                         return 1;
1422                 }
1423
1424         *iter = bch2_trans_get_iter(trans, btree_id, pos,
1425                                     BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1426         if (IS_ERR(*iter))
1427                 return PTR_ERR(*iter);
1428
1429         *k = bch2_btree_iter_peek_slot(*iter);
1430         ret = bkey_err(*k);
1431         if (ret)
1432                 bch2_trans_iter_put(trans, *iter);
1433         return ret;
1434 }
1435
1436 static int bch2_trans_mark_pointer(struct btree_trans *trans,
1437                         struct extent_ptr_decoded p,
1438                         s64 sectors, enum bch_data_type data_type)
1439 {
1440         struct bch_fs *c = trans->c;
1441         struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
1442         struct btree_iter *iter;
1443         struct bkey_s_c k;
1444         struct bkey_alloc_unpacked u;
1445         struct bkey_i_alloc *a;
1446         u16 *dst_sectors, orig_sectors;
1447         int ret;
1448
1449         ret = trans_get_key(trans, BTREE_ID_ALLOC,
1450                             POS(p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr)),
1451                             &iter, &k);
1452         if (ret < 0)
1453                 return ret;
1454
1455         if (!ret && unlikely(!test_bit(BCH_FS_ALLOC_WRITTEN, &c->flags))) {
1456                 /*
1457                  * During journal replay, and if gc repairs alloc info at
1458                  * runtime, the alloc info in the btree might not be up to date
1459                  * yet - so, trust the in memory mark:
1460                  */
1461                 struct bucket *g;
1462                 struct bucket_mark m;
1463
1464                 percpu_down_read(&c->mark_lock);
1465                 g       = bucket(ca, iter->pos.offset);
1466                 m       = READ_ONCE(g->mark);
1467                 u       = alloc_mem_to_key(g, m);
1468                 percpu_up_read(&c->mark_lock);
1469         } else {
1470                 /*
1471                  * Unless we're already updating that key:
1472                  */
1473                 if (k.k->type != KEY_TYPE_alloc) {
1474                         bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
1475                                       "pointer to nonexistent bucket %llu:%llu",
1476                                       iter->pos.inode, iter->pos.offset);
1477                         ret = -1;
1478                         goto out;
1479                 }
1480
1481                 u = bch2_alloc_unpack(k);
1482         }
1483
1484         if (gen_after(u.gen, p.ptr.gen)) {
1485                 ret = 1;
1486                 goto out;
1487         }
1488
1489         if (u.data_type && u.data_type != data_type) {
1490                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
1491                         "bucket %llu:%llu gen %u different types of data in same bucket: %s, %s",
1492                         iter->pos.inode, iter->pos.offset,
1493                         u.gen,
1494                         bch2_data_types[u.data_type],
1495                         bch2_data_types[data_type]);
1496                 ret = -1;
1497                 goto out;
1498         }
1499
1500         dst_sectors = !p.ptr.cached
1501                 ? &u.dirty_sectors
1502                 : &u.cached_sectors;
1503         orig_sectors = *dst_sectors;
1504
1505         if (checked_add(*dst_sectors, sectors)) {
1506                 bch2_fs_inconsistent(c,
1507                         "bucket sector count overflow: %u + %lli > U16_MAX",
1508                         orig_sectors, sectors);
1509                 /* return an error indicating that we need full fsck */
1510                 ret = -EIO;
1511                 goto out;
1512         }
1513
1514         u.data_type = u.dirty_sectors || u.cached_sectors
1515                 ? data_type : 0;
1516
1517         a = bch2_trans_kmalloc(trans, BKEY_ALLOC_U64s_MAX * 8);
1518         ret = PTR_ERR_OR_ZERO(a);
1519         if (ret)
1520                 goto out;
1521
1522         bkey_alloc_init(&a->k_i);
1523         a->k.p = iter->pos;
1524         bch2_alloc_pack(a, u);
1525         bch2_trans_update(trans, iter, &a->k_i, 0);
1526 out:
1527         bch2_trans_iter_put(trans, iter);
1528         return ret;
1529 }
1530
1531 static int bch2_trans_mark_stripe_ptr(struct btree_trans *trans,
1532                         struct bch_extent_stripe_ptr p,
1533                         s64 sectors, enum bch_data_type data_type,
1534                         struct bch_replicas_padded *r,
1535                         unsigned *nr_data,
1536                         unsigned *nr_parity)
1537 {
1538         struct bch_fs *c = trans->c;
1539         struct btree_iter *iter;
1540         struct bkey_s_c k;
1541         struct bkey_i_stripe *s;
1542         int ret = 0;
1543
1544         ret = trans_get_key(trans, BTREE_ID_EC, POS(0, p.idx), &iter, &k);
1545         if (ret < 0)
1546                 return ret;
1547
1548         if (k.k->type != KEY_TYPE_stripe) {
1549                 bch2_fs_inconsistent(c,
1550                         "pointer to nonexistent stripe %llu",
1551                         (u64) p.idx);
1552                 ret = -EIO;
1553                 goto out;
1554         }
1555
1556         s = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1557         ret = PTR_ERR_OR_ZERO(s);
1558         if (ret)
1559                 goto out;
1560
1561         bkey_reassemble(&s->k_i, k);
1562
1563         stripe_blockcount_set(&s->v, p.block,
1564                 stripe_blockcount_get(&s->v, p.block) +
1565                 sectors);
1566
1567         *nr_data        = s->v.nr_blocks - s->v.nr_redundant;
1568         *nr_parity      = s->v.nr_redundant;
1569         bch2_bkey_to_replicas(&r->e, bkey_i_to_s_c(&s->k_i));
1570         bch2_trans_update(trans, iter, &s->k_i, 0);
1571 out:
1572         bch2_trans_iter_put(trans, iter);
1573         return ret;
1574 }
1575
1576 static int bch2_trans_mark_extent(struct btree_trans *trans,
1577                         struct bkey_s_c k, unsigned offset,
1578                         s64 sectors, unsigned flags,
1579                         enum bch_data_type data_type)
1580 {
1581         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1582         const union bch_extent_entry *entry;
1583         struct extent_ptr_decoded p;
1584         struct bch_replicas_padded r;
1585         s64 dirty_sectors = 0;
1586         bool stale;
1587         int ret;
1588
1589         r.e.data_type   = data_type;
1590         r.e.nr_devs     = 0;
1591         r.e.nr_required = 1;
1592
1593         BUG_ON(!sectors);
1594
1595         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
1596                 s64 disk_sectors = data_type == BCH_DATA_BTREE
1597                         ? sectors
1598                         : ptr_disk_sectors_delta(p, offset, sectors, flags);
1599
1600                 ret = bch2_trans_mark_pointer(trans, p, disk_sectors,
1601                                               data_type);
1602                 if (ret < 0)
1603                         return ret;
1604
1605                 stale = ret > 0;
1606
1607                 if (p.ptr.cached) {
1608                         if (!stale)
1609                                 update_cached_sectors_list(trans, p.ptr.dev,
1610                                                            disk_sectors);
1611                 } else if (!p.has_ec) {
1612                         dirty_sectors          += disk_sectors;
1613                         r.e.devs[r.e.nr_devs++] = p.ptr.dev;
1614                 } else {
1615                         struct bch_replicas_padded ec_r;
1616                         unsigned nr_data, nr_parity;
1617                         s64 parity_sectors;
1618
1619                         ret = bch2_trans_mark_stripe_ptr(trans, p.ec,
1620                                         disk_sectors, data_type,
1621                                         &ec_r, &nr_data, &nr_parity);
1622                         if (ret)
1623                                 return ret;
1624
1625                         parity_sectors =
1626                                 __ptr_disk_sectors_delta(p.crc.live_size,
1627                                         offset, sectors, flags,
1628                                         p.crc.compressed_size * nr_parity,
1629                                         p.crc.uncompressed_size * nr_data);
1630
1631                         update_replicas_list(trans, &ec_r.e,
1632                                              disk_sectors + parity_sectors);
1633
1634                         r.e.nr_required = 0;
1635                 }
1636         }
1637
1638         if (r.e.nr_devs)
1639                 update_replicas_list(trans, &r.e, dirty_sectors);
1640
1641         return 0;
1642 }
1643
1644 static int __bch2_trans_mark_reflink_p(struct btree_trans *trans,
1645                         struct bkey_s_c_reflink_p p,
1646                         u64 idx, unsigned sectors,
1647                         unsigned flags)
1648 {
1649         struct bch_fs *c = trans->c;
1650         struct btree_iter *iter;
1651         struct bkey_s_c k;
1652         struct bkey_i_reflink_v *r_v;
1653         s64 ret;
1654
1655         ret = trans_get_key(trans, BTREE_ID_REFLINK,
1656                             POS(0, idx), &iter, &k);
1657         if (ret < 0)
1658                 return ret;
1659
1660         if (k.k->type != KEY_TYPE_reflink_v) {
1661                 bch2_fs_inconsistent(c,
1662                         "%llu:%llu len %u points to nonexistent indirect extent %llu",
1663                         p.k->p.inode, p.k->p.offset, p.k->size, idx);
1664                 ret = -EIO;
1665                 goto err;
1666         }
1667
1668         if ((flags & BTREE_TRIGGER_OVERWRITE) &&
1669             (bkey_start_offset(k.k) < idx ||
1670              k.k->p.offset > idx + sectors))
1671                 goto out;
1672
1673         sectors = k.k->p.offset - idx;
1674
1675         r_v = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1676         ret = PTR_ERR_OR_ZERO(r_v);
1677         if (ret)
1678                 goto err;
1679
1680         bkey_reassemble(&r_v->k_i, k);
1681
1682         le64_add_cpu(&r_v->v.refcount,
1683                      !(flags & BTREE_TRIGGER_OVERWRITE) ? 1 : -1);
1684
1685         if (!r_v->v.refcount) {
1686                 r_v->k.type = KEY_TYPE_deleted;
1687                 set_bkey_val_u64s(&r_v->k, 0);
1688         }
1689
1690         bch2_btree_iter_set_pos(iter, bkey_start_pos(k.k));
1691         BUG_ON(iter->uptodate > BTREE_ITER_NEED_PEEK);
1692
1693         bch2_trans_update(trans, iter, &r_v->k_i, 0);
1694 out:
1695         ret = sectors;
1696 err:
1697         bch2_trans_iter_put(trans, iter);
1698         return ret;
1699 }
1700
1701 static int bch2_trans_mark_reflink_p(struct btree_trans *trans,
1702                         struct bkey_s_c_reflink_p p, unsigned offset,
1703                         s64 sectors, unsigned flags)
1704 {
1705         u64 idx = le64_to_cpu(p.v->idx) + offset;
1706         s64 ret = 0;
1707
1708         sectors = abs(sectors);
1709         BUG_ON(offset + sectors > p.k->size);
1710
1711         while (sectors) {
1712                 ret = __bch2_trans_mark_reflink_p(trans, p, idx, sectors, flags);
1713                 if (ret < 0)
1714                         break;
1715
1716                 idx += ret;
1717                 sectors = max_t(s64, 0LL, sectors - ret);
1718                 ret = 0;
1719         }
1720
1721         return ret;
1722 }
1723
1724 int bch2_trans_mark_key(struct btree_trans *trans, struct bkey_s_c k,
1725                         unsigned offset, s64 sectors, unsigned flags)
1726 {
1727         struct replicas_delta_list *d;
1728         struct bch_fs *c = trans->c;
1729
1730         switch (k.k->type) {
1731         case KEY_TYPE_btree_ptr:
1732         case KEY_TYPE_btree_ptr_v2:
1733                 sectors = !(flags & BTREE_TRIGGER_OVERWRITE)
1734                         ?  c->opts.btree_node_size
1735                         : -c->opts.btree_node_size;
1736
1737                 return bch2_trans_mark_extent(trans, k, offset, sectors,
1738                                               flags, BCH_DATA_BTREE);
1739         case KEY_TYPE_extent:
1740         case KEY_TYPE_reflink_v:
1741                 return bch2_trans_mark_extent(trans, k, offset, sectors,
1742                                               flags, BCH_DATA_USER);
1743         case KEY_TYPE_inode:
1744                 d = replicas_deltas_realloc(trans, 0);
1745
1746                 if (!(flags & BTREE_TRIGGER_OVERWRITE))
1747                         d->nr_inodes++;
1748                 else
1749                         d->nr_inodes--;
1750                 return 0;
1751         case KEY_TYPE_reservation: {
1752                 unsigned replicas = bkey_s_c_to_reservation(k).v->nr_replicas;
1753
1754                 d = replicas_deltas_realloc(trans, 0);
1755
1756                 sectors *= replicas;
1757                 replicas = clamp_t(unsigned, replicas, 1,
1758                                    ARRAY_SIZE(d->persistent_reserved));
1759
1760                 d->persistent_reserved[replicas - 1] += sectors;
1761                 return 0;
1762         }
1763         case KEY_TYPE_reflink_p:
1764                 return bch2_trans_mark_reflink_p(trans,
1765                                         bkey_s_c_to_reflink_p(k),
1766                                         offset, sectors, flags);
1767         default:
1768                 return 0;
1769         }
1770 }
1771
1772 int bch2_trans_mark_update(struct btree_trans *trans,
1773                            struct btree_iter *iter,
1774                            struct bkey_i *insert,
1775                            unsigned flags)
1776 {
1777         struct btree            *b = iter->l[0].b;
1778         struct btree_node_iter  node_iter = iter->l[0].iter;
1779         struct bkey_packed      *_k;
1780         int ret;
1781
1782         if (unlikely(flags & BTREE_TRIGGER_NORUN))
1783                 return 0;
1784
1785         if (!btree_node_type_needs_gc(iter->btree_id))
1786                 return 0;
1787
1788         ret = bch2_trans_mark_key(trans, bkey_i_to_s_c(insert),
1789                         0, insert->k.size, BTREE_TRIGGER_INSERT);
1790         if (ret)
1791                 return ret;
1792
1793         if (unlikely(flags & BTREE_TRIGGER_NOOVERWRITES))
1794                 return 0;
1795
1796         while ((_k = bch2_btree_node_iter_peek(&node_iter, b))) {
1797                 struct bkey             unpacked;
1798                 struct bkey_s_c         k;
1799                 unsigned                offset = 0;
1800                 s64                     sectors = 0;
1801                 unsigned                flags = BTREE_TRIGGER_OVERWRITE;
1802
1803                 k = bkey_disassemble(b, _k, &unpacked);
1804
1805                 if (btree_node_is_extents(b)
1806                     ? bkey_cmp(insert->k.p, bkey_start_pos(k.k)) <= 0
1807                     : bkey_cmp(insert->k.p, k.k->p))
1808                         break;
1809
1810                 if (btree_node_is_extents(b)) {
1811                         switch (bch2_extent_overlap(&insert->k, k.k)) {
1812                         case BCH_EXTENT_OVERLAP_ALL:
1813                                 offset = 0;
1814                                 sectors = -((s64) k.k->size);
1815                                 break;
1816                         case BCH_EXTENT_OVERLAP_BACK:
1817                                 offset = bkey_start_offset(&insert->k) -
1818                                         bkey_start_offset(k.k);
1819                                 sectors = bkey_start_offset(&insert->k) -
1820                                         k.k->p.offset;
1821                                 break;
1822                         case BCH_EXTENT_OVERLAP_FRONT:
1823                                 offset = 0;
1824                                 sectors = bkey_start_offset(k.k) -
1825                                         insert->k.p.offset;
1826                                 break;
1827                         case BCH_EXTENT_OVERLAP_MIDDLE:
1828                                 offset = bkey_start_offset(&insert->k) -
1829                                         bkey_start_offset(k.k);
1830                                 sectors = -((s64) insert->k.size);
1831                                 flags |= BTREE_TRIGGER_OVERWRITE_SPLIT;
1832                                 break;
1833                         }
1834
1835                         BUG_ON(sectors >= 0);
1836                 }
1837
1838                 ret = bch2_trans_mark_key(trans, k, offset, sectors, flags);
1839                 if (ret)
1840                         return ret;
1841
1842                 bch2_btree_node_iter_advance(&node_iter, b);
1843         }
1844
1845         return 0;
1846 }
1847
1848 /* Disk reservations: */
1849
1850 static u64 bch2_recalc_sectors_available(struct bch_fs *c)
1851 {
1852         percpu_u64_set(&c->pcpu->sectors_available, 0);
1853
1854         return avail_factor(__bch2_fs_usage_read_short(c).free);
1855 }
1856
1857 void __bch2_disk_reservation_put(struct bch_fs *c, struct disk_reservation *res)
1858 {
1859         percpu_down_read(&c->mark_lock);
1860         this_cpu_sub(c->usage[0]->online_reserved,
1861                      res->sectors);
1862         percpu_up_read(&c->mark_lock);
1863
1864         res->sectors = 0;
1865 }
1866
1867 #define SECTORS_CACHE   1024
1868
1869 int bch2_disk_reservation_add(struct bch_fs *c, struct disk_reservation *res,
1870                               unsigned sectors, int flags)
1871 {
1872         struct bch_fs_pcpu *pcpu;
1873         u64 old, v, get;
1874         s64 sectors_available;
1875         int ret;
1876
1877         percpu_down_read(&c->mark_lock);
1878         preempt_disable();
1879         pcpu = this_cpu_ptr(c->pcpu);
1880
1881         if (sectors <= pcpu->sectors_available)
1882                 goto out;
1883
1884         v = atomic64_read(&c->sectors_available);
1885         do {
1886                 old = v;
1887                 get = min((u64) sectors + SECTORS_CACHE, old);
1888
1889                 if (get < sectors) {
1890                         preempt_enable();
1891                         percpu_up_read(&c->mark_lock);
1892                         goto recalculate;
1893                 }
1894         } while ((v = atomic64_cmpxchg(&c->sectors_available,
1895                                        old, old - get)) != old);
1896
1897         pcpu->sectors_available         += get;
1898
1899 out:
1900         pcpu->sectors_available         -= sectors;
1901         this_cpu_add(c->usage[0]->online_reserved, sectors);
1902         res->sectors                    += sectors;
1903
1904         preempt_enable();
1905         percpu_up_read(&c->mark_lock);
1906         return 0;
1907
1908 recalculate:
1909         percpu_down_write(&c->mark_lock);
1910
1911         sectors_available = bch2_recalc_sectors_available(c);
1912
1913         if (sectors <= sectors_available ||
1914             (flags & BCH_DISK_RESERVATION_NOFAIL)) {
1915                 atomic64_set(&c->sectors_available,
1916                              max_t(s64, 0, sectors_available - sectors));
1917                 this_cpu_add(c->usage[0]->online_reserved, sectors);
1918                 res->sectors                    += sectors;
1919                 ret = 0;
1920         } else {
1921                 atomic64_set(&c->sectors_available, sectors_available);
1922                 ret = -ENOSPC;
1923         }
1924
1925         percpu_up_write(&c->mark_lock);
1926
1927         return ret;
1928 }
1929
1930 /* Startup/shutdown: */
1931
1932 static void buckets_free_rcu(struct rcu_head *rcu)
1933 {
1934         struct bucket_array *buckets =
1935                 container_of(rcu, struct bucket_array, rcu);
1936
1937         kvpfree(buckets,
1938                 sizeof(struct bucket_array) +
1939                 buckets->nbuckets * sizeof(struct bucket));
1940 }
1941
1942 int bch2_dev_buckets_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets)
1943 {
1944         struct bucket_array *buckets = NULL, *old_buckets = NULL;
1945         unsigned long *buckets_nouse = NULL;
1946         alloc_fifo      free[RESERVE_NR];
1947         alloc_fifo      free_inc;
1948         alloc_heap      alloc_heap;
1949         copygc_heap     copygc_heap;
1950
1951         size_t btree_reserve    = DIV_ROUND_UP(BTREE_NODE_RESERVE,
1952                              ca->mi.bucket_size / c->opts.btree_node_size);
1953         /* XXX: these should be tunable */
1954         size_t reserve_none     = max_t(size_t, 1, nbuckets >> 9);
1955         size_t copygc_reserve   = max_t(size_t, 2, nbuckets >> 7);
1956         size_t free_inc_nr      = max(max_t(size_t, 1, nbuckets >> 12),
1957                                       btree_reserve * 2);
1958         bool resize = ca->buckets[0] != NULL,
1959              start_copygc = ca->copygc_thread != NULL;
1960         int ret = -ENOMEM;
1961         unsigned i;
1962
1963         memset(&free,           0, sizeof(free));
1964         memset(&free_inc,       0, sizeof(free_inc));
1965         memset(&alloc_heap,     0, sizeof(alloc_heap));
1966         memset(&copygc_heap,    0, sizeof(copygc_heap));
1967
1968         if (!(buckets           = kvpmalloc(sizeof(struct bucket_array) +
1969                                             nbuckets * sizeof(struct bucket),
1970                                             GFP_KERNEL|__GFP_ZERO)) ||
1971             !(buckets_nouse     = kvpmalloc(BITS_TO_LONGS(nbuckets) *
1972                                             sizeof(unsigned long),
1973                                             GFP_KERNEL|__GFP_ZERO)) ||
1974             !init_fifo(&free[RESERVE_BTREE], btree_reserve, GFP_KERNEL) ||
1975             !init_fifo(&free[RESERVE_MOVINGGC],
1976                        copygc_reserve, GFP_KERNEL) ||
1977             !init_fifo(&free[RESERVE_NONE], reserve_none, GFP_KERNEL) ||
1978             !init_fifo(&free_inc,       free_inc_nr, GFP_KERNEL) ||
1979             !init_heap(&alloc_heap,     ALLOC_SCAN_BATCH(ca) << 1, GFP_KERNEL) ||
1980             !init_heap(&copygc_heap,    copygc_reserve, GFP_KERNEL))
1981                 goto err;
1982
1983         buckets->first_bucket   = ca->mi.first_bucket;
1984         buckets->nbuckets       = nbuckets;
1985
1986         bch2_copygc_stop(ca);
1987
1988         if (resize) {
1989                 down_write(&c->gc_lock);
1990                 down_write(&ca->bucket_lock);
1991                 percpu_down_write(&c->mark_lock);
1992         }
1993
1994         old_buckets = bucket_array(ca);
1995
1996         if (resize) {
1997                 size_t n = min(buckets->nbuckets, old_buckets->nbuckets);
1998
1999                 memcpy(buckets->b,
2000                        old_buckets->b,
2001                        n * sizeof(struct bucket));
2002                 memcpy(buckets_nouse,
2003                        ca->buckets_nouse,
2004                        BITS_TO_LONGS(n) * sizeof(unsigned long));
2005         }
2006
2007         rcu_assign_pointer(ca->buckets[0], buckets);
2008         buckets = old_buckets;
2009
2010         swap(ca->buckets_nouse, buckets_nouse);
2011
2012         if (resize)
2013                 percpu_up_write(&c->mark_lock);
2014
2015         spin_lock(&c->freelist_lock);
2016         for (i = 0; i < RESERVE_NR; i++) {
2017                 fifo_move(&free[i], &ca->free[i]);
2018                 swap(ca->free[i], free[i]);
2019         }
2020         fifo_move(&free_inc, &ca->free_inc);
2021         swap(ca->free_inc, free_inc);
2022         spin_unlock(&c->freelist_lock);
2023
2024         /* with gc lock held, alloc_heap can't be in use: */
2025         swap(ca->alloc_heap, alloc_heap);
2026
2027         /* and we shut down copygc: */
2028         swap(ca->copygc_heap, copygc_heap);
2029
2030         nbuckets = ca->mi.nbuckets;
2031
2032         if (resize) {
2033                 up_write(&ca->bucket_lock);
2034                 up_write(&c->gc_lock);
2035         }
2036
2037         if (start_copygc &&
2038             bch2_copygc_start(c, ca))
2039                 bch_err(ca, "error restarting copygc thread");
2040
2041         ret = 0;
2042 err:
2043         free_heap(&copygc_heap);
2044         free_heap(&alloc_heap);
2045         free_fifo(&free_inc);
2046         for (i = 0; i < RESERVE_NR; i++)
2047                 free_fifo(&free[i]);
2048         kvpfree(buckets_nouse,
2049                 BITS_TO_LONGS(nbuckets) * sizeof(unsigned long));
2050         if (buckets)
2051                 call_rcu(&old_buckets->rcu, buckets_free_rcu);
2052
2053         return ret;
2054 }
2055
2056 void bch2_dev_buckets_free(struct bch_dev *ca)
2057 {
2058         unsigned i;
2059
2060         free_heap(&ca->copygc_heap);
2061         free_heap(&ca->alloc_heap);
2062         free_fifo(&ca->free_inc);
2063         for (i = 0; i < RESERVE_NR; i++)
2064                 free_fifo(&ca->free[i]);
2065         kvpfree(ca->buckets_nouse,
2066                 BITS_TO_LONGS(ca->mi.nbuckets) * sizeof(unsigned long));
2067         kvpfree(rcu_dereference_protected(ca->buckets[0], 1),
2068                 sizeof(struct bucket_array) +
2069                 ca->mi.nbuckets * sizeof(struct bucket));
2070
2071         free_percpu(ca->usage[0]);
2072 }
2073
2074 int bch2_dev_buckets_alloc(struct bch_fs *c, struct bch_dev *ca)
2075 {
2076         if (!(ca->usage[0] = alloc_percpu(struct bch_dev_usage)))
2077                 return -ENOMEM;
2078
2079         return bch2_dev_buckets_resize(c, ca, ca->mi.nbuckets);;
2080 }