]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/buckets.c
2c3b71b2f04ed2300bb65752b31a20f743ab2be9
[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
8 #include "bcachefs.h"
9 #include "alloc_background.h"
10 #include "bset.h"
11 #include "btree_gc.h"
12 #include "btree_update.h"
13 #include "buckets.h"
14 #include "buckets_waiting_for_journal.h"
15 #include "ec.h"
16 #include "error.h"
17 #include "inode.h"
18 #include "movinggc.h"
19 #include "recovery.h"
20 #include "reflink.h"
21 #include "replicas.h"
22 #include "subvolume.h"
23
24 #include <linux/preempt.h>
25 #include <trace/events/bcachefs.h>
26
27 static inline void fs_usage_data_type_to_base(struct bch_fs_usage *fs_usage,
28                                               enum bch_data_type data_type,
29                                               s64 sectors)
30 {
31         switch (data_type) {
32         case BCH_DATA_btree:
33                 fs_usage->btree         += sectors;
34                 break;
35         case BCH_DATA_user:
36         case BCH_DATA_parity:
37                 fs_usage->data          += sectors;
38                 break;
39         case BCH_DATA_cached:
40                 fs_usage->cached        += sectors;
41                 break;
42         default:
43                 break;
44         }
45 }
46
47 void bch2_fs_usage_initialize(struct bch_fs *c)
48 {
49         struct bch_fs_usage *usage;
50         struct bch_dev *ca;
51         unsigned i;
52
53         percpu_down_write(&c->mark_lock);
54         usage = c->usage_base;
55
56         for (i = 0; i < ARRAY_SIZE(c->usage); i++)
57                 bch2_fs_usage_acc_to_base(c, i);
58
59         for (i = 0; i < BCH_REPLICAS_MAX; i++)
60                 usage->reserved += usage->persistent_reserved[i];
61
62         for (i = 0; i < c->replicas.nr; i++) {
63                 struct bch_replicas_entry *e =
64                         cpu_replicas_entry(&c->replicas, i);
65
66                 fs_usage_data_type_to_base(usage, e->data_type, usage->replicas[i]);
67         }
68
69         for_each_member_device(ca, c, i) {
70                 struct bch_dev_usage dev = bch2_dev_usage_read(ca);
71
72                 usage->hidden += (dev.d[BCH_DATA_sb].buckets +
73                                   dev.d[BCH_DATA_journal].buckets) *
74                         ca->mi.bucket_size;
75         }
76
77         percpu_up_write(&c->mark_lock);
78 }
79
80 static inline struct bch_dev_usage *dev_usage_ptr(struct bch_dev *ca,
81                                                   unsigned journal_seq,
82                                                   bool gc)
83 {
84         BUG_ON(!gc && !journal_seq);
85
86         return this_cpu_ptr(gc
87                             ? ca->usage_gc
88                             : ca->usage[journal_seq & JOURNAL_BUF_MASK]);
89 }
90
91 struct bch_dev_usage bch2_dev_usage_read(struct bch_dev *ca)
92 {
93         struct bch_fs *c = ca->fs;
94         struct bch_dev_usage ret;
95         unsigned seq, i, u64s = dev_usage_u64s();
96
97         do {
98                 seq = read_seqcount_begin(&c->usage_lock);
99                 memcpy(&ret, ca->usage_base, u64s * sizeof(u64));
100                 for (i = 0; i < ARRAY_SIZE(ca->usage); i++)
101                         acc_u64s_percpu((u64 *) &ret, (u64 __percpu *) ca->usage[i], u64s);
102         } while (read_seqcount_retry(&c->usage_lock, seq));
103
104         return ret;
105 }
106
107 static inline struct bch_fs_usage *fs_usage_ptr(struct bch_fs *c,
108                                                 unsigned journal_seq,
109                                                 bool gc)
110 {
111         percpu_rwsem_assert_held(&c->mark_lock);
112         BUG_ON(!gc && !journal_seq);
113
114         return this_cpu_ptr(gc
115                             ? c->usage_gc
116                             : c->usage[journal_seq & JOURNAL_BUF_MASK]);
117 }
118
119 u64 bch2_fs_usage_read_one(struct bch_fs *c, u64 *v)
120 {
121         ssize_t offset = v - (u64 *) c->usage_base;
122         unsigned i, seq;
123         u64 ret;
124
125         BUG_ON(offset < 0 || offset >= fs_usage_u64s(c));
126         percpu_rwsem_assert_held(&c->mark_lock);
127
128         do {
129                 seq = read_seqcount_begin(&c->usage_lock);
130                 ret = *v;
131
132                 for (i = 0; i < ARRAY_SIZE(c->usage); i++)
133                         ret += percpu_u64_get((u64 __percpu *) c->usage[i] + offset);
134         } while (read_seqcount_retry(&c->usage_lock, seq));
135
136         return ret;
137 }
138
139 struct bch_fs_usage_online *bch2_fs_usage_read(struct bch_fs *c)
140 {
141         struct bch_fs_usage_online *ret;
142         unsigned seq, i, u64s;
143
144         percpu_down_read(&c->mark_lock);
145
146         ret = kmalloc(sizeof(struct bch_fs_usage_online) +
147                       sizeof(u64) * c->replicas.nr, GFP_NOFS);
148         if (unlikely(!ret)) {
149                 percpu_up_read(&c->mark_lock);
150                 return NULL;
151         }
152
153         ret->online_reserved = percpu_u64_get(c->online_reserved);
154
155         u64s = fs_usage_u64s(c);
156         do {
157                 seq = read_seqcount_begin(&c->usage_lock);
158                 memcpy(&ret->u, c->usage_base, u64s * sizeof(u64));
159                 for (i = 0; i < ARRAY_SIZE(c->usage); i++)
160                         acc_u64s_percpu((u64 *) &ret->u, (u64 __percpu *) c->usage[i], u64s);
161         } while (read_seqcount_retry(&c->usage_lock, seq));
162
163         return ret;
164 }
165
166 void bch2_fs_usage_acc_to_base(struct bch_fs *c, unsigned idx)
167 {
168         struct bch_dev *ca;
169         unsigned i, u64s = fs_usage_u64s(c);
170
171         BUG_ON(idx >= ARRAY_SIZE(c->usage));
172
173         preempt_disable();
174         write_seqcount_begin(&c->usage_lock);
175
176         acc_u64s_percpu((u64 *) c->usage_base,
177                         (u64 __percpu *) c->usage[idx], u64s);
178         percpu_memset(c->usage[idx], 0, u64s * sizeof(u64));
179
180         rcu_read_lock();
181         for_each_member_device_rcu(ca, c, i, NULL) {
182                 u64s = dev_usage_u64s();
183
184                 acc_u64s_percpu((u64 *) ca->usage_base,
185                                 (u64 __percpu *) ca->usage[idx], u64s);
186                 percpu_memset(ca->usage[idx], 0, u64s * sizeof(u64));
187         }
188         rcu_read_unlock();
189
190         write_seqcount_end(&c->usage_lock);
191         preempt_enable();
192 }
193
194 void bch2_fs_usage_to_text(struct printbuf *out,
195                            struct bch_fs *c,
196                            struct bch_fs_usage_online *fs_usage)
197 {
198         unsigned i;
199
200         pr_buf(out, "capacity:\t\t\t%llu\n", c->capacity);
201
202         pr_buf(out, "hidden:\t\t\t\t%llu\n",
203                fs_usage->u.hidden);
204         pr_buf(out, "data:\t\t\t\t%llu\n",
205                fs_usage->u.data);
206         pr_buf(out, "cached:\t\t\t\t%llu\n",
207                fs_usage->u.cached);
208         pr_buf(out, "reserved:\t\t\t%llu\n",
209                fs_usage->u.reserved);
210         pr_buf(out, "nr_inodes:\t\t\t%llu\n",
211                fs_usage->u.nr_inodes);
212         pr_buf(out, "online reserved:\t\t%llu\n",
213                fs_usage->online_reserved);
214
215         for (i = 0;
216              i < ARRAY_SIZE(fs_usage->u.persistent_reserved);
217              i++) {
218                 pr_buf(out, "%u replicas:\n", i + 1);
219                 pr_buf(out, "\treserved:\t\t%llu\n",
220                        fs_usage->u.persistent_reserved[i]);
221         }
222
223         for (i = 0; i < c->replicas.nr; i++) {
224                 struct bch_replicas_entry *e =
225                         cpu_replicas_entry(&c->replicas, i);
226
227                 pr_buf(out, "\t");
228                 bch2_replicas_entry_to_text(out, e);
229                 pr_buf(out, ":\t%llu\n", fs_usage->u.replicas[i]);
230         }
231 }
232
233 static u64 reserve_factor(u64 r)
234 {
235         return r + (round_up(r, (1 << RESERVE_FACTOR)) >> RESERVE_FACTOR);
236 }
237
238 u64 bch2_fs_sectors_used(struct bch_fs *c, struct bch_fs_usage_online *fs_usage)
239 {
240         return min(fs_usage->u.hidden +
241                    fs_usage->u.btree +
242                    fs_usage->u.data +
243                    reserve_factor(fs_usage->u.reserved +
244                                   fs_usage->online_reserved),
245                    c->capacity);
246 }
247
248 static struct bch_fs_usage_short
249 __bch2_fs_usage_read_short(struct bch_fs *c)
250 {
251         struct bch_fs_usage_short ret;
252         u64 data, reserved;
253
254         ret.capacity = c->capacity -
255                 bch2_fs_usage_read_one(c, &c->usage_base->hidden);
256
257         data            = bch2_fs_usage_read_one(c, &c->usage_base->data) +
258                 bch2_fs_usage_read_one(c, &c->usage_base->btree);
259         reserved        = bch2_fs_usage_read_one(c, &c->usage_base->reserved) +
260                 percpu_u64_get(c->online_reserved);
261
262         ret.used        = min(ret.capacity, data + reserve_factor(reserved));
263         ret.free        = ret.capacity - ret.used;
264
265         ret.nr_inodes   = bch2_fs_usage_read_one(c, &c->usage_base->nr_inodes);
266
267         return ret;
268 }
269
270 struct bch_fs_usage_short
271 bch2_fs_usage_read_short(struct bch_fs *c)
272 {
273         struct bch_fs_usage_short ret;
274
275         percpu_down_read(&c->mark_lock);
276         ret = __bch2_fs_usage_read_short(c);
277         percpu_up_read(&c->mark_lock);
278
279         return ret;
280 }
281
282 static inline int is_unavailable_bucket(struct bucket_mark m)
283 {
284         return !is_available_bucket(m);
285 }
286
287 static inline int bucket_sectors_fragmented(struct bch_dev *ca,
288                                             struct bucket_mark m)
289 {
290         return m.dirty_sectors
291                 ? max(0, (int) ca->mi.bucket_size - (int) m.dirty_sectors)
292                 : 0;
293 }
294
295 static inline int is_stripe_data_bucket(struct bucket_mark m)
296 {
297         return m.stripe && m.data_type != BCH_DATA_parity;
298 }
299
300 static inline enum bch_data_type bucket_type(struct bucket_mark m)
301 {
302         return m.cached_sectors && !m.dirty_sectors
303                 ? BCH_DATA_cached
304                 : m.data_type;
305 }
306
307 static inline void account_bucket(struct bch_fs_usage *fs_usage,
308                                   struct bch_dev_usage *dev_usage,
309                                   enum bch_data_type type,
310                                   int nr, s64 size)
311 {
312         if (type == BCH_DATA_sb || type == BCH_DATA_journal)
313                 fs_usage->hidden        += size;
314
315         dev_usage->d[type].buckets      += nr;
316 }
317
318 static void bch2_dev_usage_update(struct bch_fs *c, struct bch_dev *ca,
319                                   struct bucket_mark old, struct bucket_mark new,
320                                   u64 journal_seq, bool gc)
321 {
322         struct bch_fs_usage *fs_usage;
323         struct bch_dev_usage *u;
324
325         preempt_disable();
326         fs_usage = fs_usage_ptr(c, journal_seq, gc);
327         u = dev_usage_ptr(ca, journal_seq, gc);
328
329         if (bucket_type(old))
330                 account_bucket(fs_usage, u, bucket_type(old),
331                                -1, -ca->mi.bucket_size);
332
333         if (bucket_type(new))
334                 account_bucket(fs_usage, u, bucket_type(new),
335                                1, ca->mi.bucket_size);
336
337         u->buckets_ec += (int) new.stripe - (int) old.stripe;
338         u->buckets_unavailable +=
339                 is_unavailable_bucket(new) - is_unavailable_bucket(old);
340
341         u->d[old.data_type].sectors -= old.dirty_sectors;
342         u->d[new.data_type].sectors += new.dirty_sectors;
343         u->d[BCH_DATA_cached].sectors +=
344                 (int) new.cached_sectors - (int) old.cached_sectors;
345
346         u->d[old.data_type].fragmented -= bucket_sectors_fragmented(ca, old);
347         u->d[new.data_type].fragmented += bucket_sectors_fragmented(ca, new);
348
349         preempt_enable();
350
351         if (!is_available_bucket(old) && is_available_bucket(new))
352                 bch2_wake_allocator(ca);
353 }
354
355 static inline int __update_replicas(struct bch_fs *c,
356                                     struct bch_fs_usage *fs_usage,
357                                     struct bch_replicas_entry *r,
358                                     s64 sectors)
359 {
360         int idx = bch2_replicas_entry_idx(c, r);
361
362         if (idx < 0)
363                 return -1;
364
365         fs_usage_data_type_to_base(fs_usage, r->data_type, sectors);
366         fs_usage->replicas[idx]         += sectors;
367         return 0;
368 }
369
370 static inline int update_replicas(struct bch_fs *c, struct bkey_s_c k,
371                         struct bch_replicas_entry *r, s64 sectors,
372                         unsigned journal_seq, bool gc)
373 {
374         struct bch_fs_usage __percpu *fs_usage;
375         int idx, ret = 0;
376         struct printbuf buf = PRINTBUF;
377
378         percpu_down_read(&c->mark_lock);
379         buf.atomic++;
380
381         idx = bch2_replicas_entry_idx(c, r);
382         if (idx < 0 &&
383             (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
384              fsck_err(c, "no replicas entry\n"
385                       "  while marking %s",
386                       (bch2_bkey_val_to_text(&buf, c, k), buf.buf)))) {
387                 percpu_up_read(&c->mark_lock);
388                 ret = bch2_mark_replicas(c, r);
389                 percpu_down_read(&c->mark_lock);
390
391                 if (ret)
392                         goto err;
393                 idx = bch2_replicas_entry_idx(c, r);
394         }
395         if (idx < 0) {
396                 ret = -1;
397                 goto err;
398         }
399
400         preempt_disable();
401         fs_usage = fs_usage_ptr(c, journal_seq, gc);
402         fs_usage_data_type_to_base(fs_usage, r->data_type, sectors);
403         fs_usage->replicas[idx]         += sectors;
404         preempt_enable();
405 err:
406 fsck_err:
407         percpu_up_read(&c->mark_lock);
408         printbuf_exit(&buf);
409         return ret;
410 }
411
412 static inline int update_cached_sectors(struct bch_fs *c,
413                         struct bkey_s_c k,
414                         unsigned dev, s64 sectors,
415                         unsigned journal_seq, bool gc)
416 {
417         struct bch_replicas_padded r;
418
419         bch2_replicas_entry_cached(&r.e, dev);
420
421         return update_replicas(c, k, &r.e, sectors, journal_seq, gc);
422 }
423
424 static struct replicas_delta_list *
425 replicas_deltas_realloc(struct btree_trans *trans, unsigned more)
426 {
427         struct replicas_delta_list *d = trans->fs_usage_deltas;
428         unsigned new_size = d ? (d->size + more) * 2 : 128;
429         unsigned alloc_size = sizeof(*d) + new_size;
430
431         WARN_ON_ONCE(alloc_size > REPLICAS_DELTA_LIST_MAX);
432
433         if (!d || d->used + more > d->size) {
434                 d = krealloc(d, alloc_size, GFP_NOIO|__GFP_ZERO);
435
436                 BUG_ON(!d && alloc_size > REPLICAS_DELTA_LIST_MAX);
437
438                 if (!d) {
439                         d = mempool_alloc(&trans->c->replicas_delta_pool, GFP_NOIO);
440                         memset(d, 0, REPLICAS_DELTA_LIST_MAX);
441
442                         if (trans->fs_usage_deltas)
443                                 memcpy(d, trans->fs_usage_deltas,
444                                        trans->fs_usage_deltas->size + sizeof(*d));
445
446                         new_size = REPLICAS_DELTA_LIST_MAX - sizeof(*d);
447                         kfree(trans->fs_usage_deltas);
448                 }
449
450                 d->size = new_size;
451                 trans->fs_usage_deltas = d;
452         }
453         return d;
454 }
455
456 static inline void update_replicas_list(struct btree_trans *trans,
457                                         struct bch_replicas_entry *r,
458                                         s64 sectors)
459 {
460         struct replicas_delta_list *d;
461         struct replicas_delta *n;
462         unsigned b;
463
464         if (!sectors)
465                 return;
466
467         b = replicas_entry_bytes(r) + 8;
468         d = replicas_deltas_realloc(trans, b);
469
470         n = (void *) d->d + d->used;
471         n->delta = sectors;
472         memcpy(&n->r, r, replicas_entry_bytes(r));
473         bch2_replicas_entry_sort(&n->r);
474         d->used += b;
475 }
476
477 static inline void update_cached_sectors_list(struct btree_trans *trans,
478                                               unsigned dev, s64 sectors)
479 {
480         struct bch_replicas_padded r;
481
482         bch2_replicas_entry_cached(&r.e, dev);
483
484         update_replicas_list(trans, &r.e, sectors);
485 }
486
487 void bch2_mark_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
488                             size_t b, bool owned_by_allocator)
489 {
490         struct bucket *g = bucket(ca, b);
491         struct bucket_mark old, new;
492
493         old = bucket_cmpxchg(g, new, ({
494                 new.owned_by_allocator  = owned_by_allocator;
495         }));
496
497         BUG_ON(owned_by_allocator == old.owned_by_allocator);
498 }
499
500 static int bch2_mark_alloc(struct btree_trans *trans,
501                            struct bkey_s_c old, struct bkey_s_c new,
502                            unsigned flags)
503 {
504         bool gc = flags & BTREE_TRIGGER_GC;
505         u64 journal_seq = trans->journal_res.seq;
506         struct bch_fs *c = trans->c;
507         struct bkey_alloc_unpacked old_u = bch2_alloc_unpack(old);
508         struct bkey_alloc_unpacked new_u = bch2_alloc_unpack(new);
509         struct bch_dev *ca;
510         struct bucket *g;
511         struct bucket_mark old_m, m;
512         int ret = 0;
513
514         /*
515          * alloc btree is read in by bch2_alloc_read, not gc:
516          */
517         if ((flags & BTREE_TRIGGER_GC) &&
518             !(flags & BTREE_TRIGGER_BUCKET_INVALIDATE))
519                 return 0;
520
521         if ((flags & BTREE_TRIGGER_INSERT) &&
522             !old_u.data_type != !new_u.data_type &&
523             new.k->type == KEY_TYPE_alloc_v3) {
524                 struct bch_alloc_v3 *v = (struct bch_alloc_v3 *) new.v;
525                 u64 old_journal_seq = le64_to_cpu(v->journal_seq);
526
527                 BUG_ON(!journal_seq);
528
529                 /*
530                  * If the btree updates referring to a bucket weren't flushed
531                  * before the bucket became empty again, then the we don't have
532                  * to wait on a journal flush before we can reuse the bucket:
533                  */
534                 new_u.journal_seq = !new_u.data_type &&
535                         (journal_seq == old_journal_seq ||
536                          bch2_journal_noflush_seq(&c->journal, old_journal_seq))
537                         ? 0 : journal_seq;
538                 v->journal_seq = cpu_to_le64(new_u.journal_seq);
539         }
540
541         if (old_u.data_type && !new_u.data_type && new_u.journal_seq) {
542                 ret = bch2_set_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
543                                 c->journal.flushed_seq_ondisk,
544                                 new_u.dev, new_u.bucket,
545                                 new_u.journal_seq);
546                 if (ret) {
547                         bch2_fs_fatal_error(c,
548                                 "error setting bucket_needs_journal_commit: %i", ret);
549                         return ret;
550                 }
551         }
552
553         ca = bch_dev_bkey_exists(c, new_u.dev);
554
555         if (new_u.bucket >= ca->mi.nbuckets)
556                 return 0;
557
558         percpu_down_read(&c->mark_lock);
559         if (!gc && new_u.gen != old_u.gen)
560                 *bucket_gen(ca, new_u.bucket) = new_u.gen;
561
562         g = __bucket(ca, new_u.bucket, gc);
563
564         old_m = bucket_cmpxchg(g, m, ({
565                 m.gen                   = new_u.gen;
566                 m.data_type             = new_u.data_type;
567                 m.dirty_sectors         = new_u.dirty_sectors;
568                 m.cached_sectors        = new_u.cached_sectors;
569                 m.stripe                = new_u.stripe != 0;
570         }));
571
572         bch2_dev_usage_update(c, ca, old_m, m, journal_seq, gc);
573
574         g->io_time[READ]        = new_u.read_time;
575         g->io_time[WRITE]       = new_u.write_time;
576         g->oldest_gen           = new_u.oldest_gen;
577         g->gen_valid            = 1;
578         g->stripe               = new_u.stripe;
579         g->stripe_redundancy    = new_u.stripe_redundancy;
580         percpu_up_read(&c->mark_lock);
581
582         /*
583          * need to know if we're getting called from the invalidate path or
584          * not:
585          */
586
587         if ((flags & BTREE_TRIGGER_BUCKET_INVALIDATE) &&
588             old_m.cached_sectors) {
589                 ret = update_cached_sectors(c, new, ca->dev_idx,
590                                             -old_m.cached_sectors,
591                                             journal_seq, gc);
592                 if (ret) {
593                         bch2_fs_fatal_error(c, "bch2_mark_alloc(): no replicas entry while updating cached sectors");
594                         return ret;
595                 }
596
597                 trace_invalidate(ca, bucket_to_sector(ca, new_u.bucket),
598                                  old_m.cached_sectors);
599         }
600
601         return 0;
602 }
603
604 #define checked_add(a, b)                                       \
605 ({                                                              \
606         unsigned _res = (unsigned) (a) + (b);                   \
607         bool overflow = _res > U16_MAX;                         \
608         if (overflow)                                           \
609                 _res = U16_MAX;                                 \
610         (a) = _res;                                             \
611         overflow;                                               \
612 })
613
614 void bch2_mark_metadata_bucket(struct bch_fs *c, struct bch_dev *ca,
615                                size_t b, enum bch_data_type data_type,
616                                unsigned sectors, struct gc_pos pos,
617                                unsigned flags)
618 {
619         struct bucket *g;
620         struct bucket_mark old, new;
621         bool overflow;
622
623         BUG_ON(!(flags & BTREE_TRIGGER_GC));
624         BUG_ON(data_type != BCH_DATA_sb &&
625                data_type != BCH_DATA_journal);
626
627         /*
628          * Backup superblock might be past the end of our normal usable space:
629          */
630         if (b >= ca->mi.nbuckets)
631                 return;
632
633         percpu_down_read(&c->mark_lock);
634         g = gc_bucket(ca, b);
635         old = bucket_cmpxchg(g, new, ({
636                 new.data_type   = data_type;
637                 overflow = checked_add(new.dirty_sectors, sectors);
638         }));
639
640         bch2_fs_inconsistent_on(old.data_type &&
641                                 old.data_type != data_type, c,
642                 "different types of data in same bucket: %s, %s",
643                 bch2_data_types[old.data_type],
644                 bch2_data_types[data_type]);
645
646         bch2_fs_inconsistent_on(overflow, c,
647                 "bucket %u:%zu gen %u data type %s sector count overflow: %u + %u > U16_MAX",
648                 ca->dev_idx, b, new.gen,
649                 bch2_data_types[old.data_type ?: data_type],
650                 old.dirty_sectors, sectors);
651
652         bch2_dev_usage_update(c, ca, old, new, 0, true);
653         percpu_up_read(&c->mark_lock);
654 }
655
656 static s64 ptr_disk_sectors(s64 sectors, struct extent_ptr_decoded p)
657 {
658         EBUG_ON(sectors < 0);
659
660         return p.crc.compression_type &&
661                 p.crc.compression_type != BCH_COMPRESSION_TYPE_incompressible
662                 ? DIV_ROUND_UP_ULL(sectors * p.crc.compressed_size,
663                                p.crc.uncompressed_size)
664                 : sectors;
665 }
666
667 static int check_bucket_ref(struct bch_fs *c,
668                             struct bkey_s_c k,
669                             const struct bch_extent_ptr *ptr,
670                             s64 sectors, enum bch_data_type ptr_data_type,
671                             u8 b_gen, u8 bucket_data_type,
672                             u16 dirty_sectors, u16 cached_sectors)
673 {
674         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
675         size_t bucket_nr = PTR_BUCKET_NR(ca, ptr);
676         u16 bucket_sectors = !ptr->cached
677                 ? dirty_sectors
678                 : cached_sectors;
679         struct printbuf buf = PRINTBUF;
680         int ret = 0;
681
682         if (gen_after(ptr->gen, b_gen)) {
683                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
684                         "bucket %u:%zu gen %u data type %s: ptr gen %u newer than bucket gen\n"
685                         "while marking %s",
686                         ptr->dev, bucket_nr, b_gen,
687                         bch2_data_types[bucket_data_type ?: ptr_data_type],
688                         ptr->gen,
689                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf));
690                 ret = -EIO;
691                 goto err;
692         }
693
694         if (gen_cmp(b_gen, ptr->gen) > BUCKET_GC_GEN_MAX) {
695                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
696                         "bucket %u:%zu gen %u data type %s: ptr gen %u too stale\n"
697                         "while marking %s",
698                         ptr->dev, bucket_nr, b_gen,
699                         bch2_data_types[bucket_data_type ?: ptr_data_type],
700                         ptr->gen,
701                         (printbuf_reset(&buf),
702                          bch2_bkey_val_to_text(&buf, c, k), buf.buf));
703                 ret = -EIO;
704                 goto err;
705         }
706
707         if (b_gen != ptr->gen && !ptr->cached) {
708                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
709                         "bucket %u:%zu gen %u (mem gen %u) data type %s: stale dirty ptr (gen %u)\n"
710                         "while marking %s",
711                         ptr->dev, bucket_nr, b_gen,
712                         *bucket_gen(ca, bucket_nr),
713                         bch2_data_types[bucket_data_type ?: ptr_data_type],
714                         ptr->gen,
715                         (printbuf_reset(&buf),
716                          bch2_bkey_val_to_text(&buf, c, k), buf.buf));
717                 ret = -EIO;
718                 goto err;
719         }
720
721         if (b_gen != ptr->gen) {
722                 ret = 1;
723                 goto err;
724         }
725
726         if (bucket_data_type && ptr_data_type &&
727             bucket_data_type != ptr_data_type) {
728                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
729                         "bucket %u:%zu gen %u different types of data in same bucket: %s, %s\n"
730                         "while marking %s",
731                         ptr->dev, bucket_nr, b_gen,
732                         bch2_data_types[bucket_data_type],
733                         bch2_data_types[ptr_data_type],
734                         (printbuf_reset(&buf),
735                          bch2_bkey_val_to_text(&buf, c, k), buf.buf));
736                 ret = -EIO;
737                 goto err;
738         }
739
740         if ((unsigned) (bucket_sectors + sectors) > U16_MAX) {
741                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
742                         "bucket %u:%zu gen %u data type %s sector count overflow: %u + %lli > U16_MAX\n"
743                         "while marking %s",
744                         ptr->dev, bucket_nr, b_gen,
745                         bch2_data_types[bucket_data_type ?: ptr_data_type],
746                         bucket_sectors, sectors,
747                         (printbuf_reset(&buf),
748                          bch2_bkey_val_to_text(&buf, c, k), buf.buf));
749                 ret = -EIO;
750                 goto err;
751         }
752 err:
753         printbuf_exit(&buf);
754         return ret;
755 }
756
757 static int mark_stripe_bucket(struct btree_trans *trans,
758                               struct bkey_s_c k,
759                               unsigned ptr_idx,
760                               unsigned flags)
761 {
762         struct bch_fs *c = trans->c;
763         u64 journal_seq = trans->journal_res.seq;
764         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
765         unsigned nr_data = s->nr_blocks - s->nr_redundant;
766         bool parity = ptr_idx >= nr_data;
767         enum bch_data_type data_type = parity ? BCH_DATA_parity : 0;
768         s64 sectors = parity ? le16_to_cpu(s->sectors) : 0;
769         const struct bch_extent_ptr *ptr = s->ptrs + ptr_idx;
770         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
771         struct bucket *g;
772         struct bucket_mark new, old;
773         struct printbuf buf = PRINTBUF;
774         int ret = 0;
775
776         BUG_ON(!(flags & BTREE_TRIGGER_GC));
777
778         /* * XXX doesn't handle deletion */
779
780         percpu_down_read(&c->mark_lock);
781         buf.atomic++;
782         g = PTR_GC_BUCKET(ca, ptr);
783
784         if (g->mark.dirty_sectors ||
785             (g->stripe && g->stripe != k.k->p.offset)) {
786                 bch2_fs_inconsistent(c,
787                               "bucket %u:%zu gen %u: multiple stripes using same bucket\n%s",
788                               ptr->dev, PTR_BUCKET_NR(ca, ptr), g->mark.gen,
789                               (bch2_bkey_val_to_text(&buf, c, k), buf.buf));
790                 ret = -EINVAL;
791                 goto err;
792         }
793
794         old = bucket_cmpxchg(g, new, ({
795                 ret = check_bucket_ref(c, k, ptr, sectors, data_type,
796                                        new.gen, new.data_type,
797                                        new.dirty_sectors, new.cached_sectors);
798                 if (ret)
799                         goto err;
800
801                 new.dirty_sectors += sectors;
802                 if (data_type)
803                         new.data_type           = data_type;
804
805                 new.stripe = true;
806         }));
807
808         g->stripe               = k.k->p.offset;
809         g->stripe_redundancy    = s->nr_redundant;
810
811         bch2_dev_usage_update(c, ca, old, new, journal_seq, true);
812 err:
813         percpu_up_read(&c->mark_lock);
814         printbuf_exit(&buf);
815         return ret;
816 }
817
818 static int __mark_pointer(struct btree_trans *trans,
819                           struct bkey_s_c k,
820                           const struct bch_extent_ptr *ptr,
821                           s64 sectors, enum bch_data_type ptr_data_type,
822                           u8 bucket_gen, u8 *bucket_data_type,
823                           u16 *dirty_sectors, u16 *cached_sectors)
824 {
825         u16 *dst_sectors = !ptr->cached
826                 ? dirty_sectors
827                 : cached_sectors;
828         int ret = check_bucket_ref(trans->c, k, ptr, sectors, ptr_data_type,
829                                    bucket_gen, *bucket_data_type,
830                                    *dirty_sectors, *cached_sectors);
831
832         if (ret)
833                 return ret;
834
835         *dst_sectors += sectors;
836         *bucket_data_type = *dirty_sectors || *cached_sectors
837                 ? ptr_data_type : 0;
838         return 0;
839 }
840
841 static int bch2_mark_pointer(struct btree_trans *trans,
842                              struct bkey_s_c k,
843                              struct extent_ptr_decoded p,
844                              s64 sectors, enum bch_data_type data_type,
845                              unsigned flags)
846 {
847         u64 journal_seq = trans->journal_res.seq;
848         struct bch_fs *c = trans->c;
849         struct bucket_mark old, new;
850         struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
851         struct bucket *g;
852         u8 bucket_data_type;
853         u64 v;
854         int ret = 0;
855
856         BUG_ON(!(flags & BTREE_TRIGGER_GC));
857
858         percpu_down_read(&c->mark_lock);
859         g = PTR_GC_BUCKET(ca, &p.ptr);
860
861         v = atomic64_read(&g->_mark.v);
862         do {
863                 new.v.counter = old.v.counter = v;
864                 bucket_data_type = new.data_type;
865
866                 ret = __mark_pointer(trans, k, &p.ptr, sectors,
867                                      data_type, new.gen,
868                                      &bucket_data_type,
869                                      &new.dirty_sectors,
870                                      &new.cached_sectors);
871                 if (ret)
872                         goto err;
873
874                 new.data_type = bucket_data_type;
875
876                 if (flags & BTREE_TRIGGER_NOATOMIC) {
877                         g->_mark = new;
878                         break;
879                 }
880         } while ((v = atomic64_cmpxchg(&g->_mark.v,
881                               old.v.counter,
882                               new.v.counter)) != old.v.counter);
883
884         bch2_dev_usage_update(c, ca, old, new, journal_seq, true);
885 err:
886         percpu_up_read(&c->mark_lock);
887
888         return ret;
889 }
890
891 static int bch2_mark_stripe_ptr(struct btree_trans *trans,
892                                 struct bkey_s_c k,
893                                 struct bch_extent_stripe_ptr p,
894                                 enum bch_data_type data_type,
895                                 s64 sectors,
896                                 unsigned flags)
897 {
898         struct bch_fs *c = trans->c;
899         struct bch_replicas_padded r;
900         struct gc_stripe *m;
901
902         BUG_ON(!(flags & BTREE_TRIGGER_GC));
903
904         m = genradix_ptr_alloc(&c->gc_stripes, p.idx, GFP_KERNEL);
905         if (!m) {
906                 bch_err(c, "error allocating memory for gc_stripes, idx %llu",
907                         (u64) p.idx);
908                 return -ENOMEM;
909         }
910
911         spin_lock(&c->ec_stripes_heap_lock);
912
913         if (!m || !m->alive) {
914                 spin_unlock(&c->ec_stripes_heap_lock);
915                 bch_err_ratelimited(c, "pointer to nonexistent stripe %llu",
916                                     (u64) p.idx);
917                 bch2_inconsistent_error(c);
918                 return -EIO;
919         }
920
921         m->block_sectors[p.block] += sectors;
922
923         r = m->r;
924         spin_unlock(&c->ec_stripes_heap_lock);
925
926         r.e.data_type = data_type;
927         update_replicas(c, k, &r.e, sectors, trans->journal_res.seq, true);
928
929         return 0;
930 }
931
932 static int bch2_mark_extent(struct btree_trans *trans,
933                             struct bkey_s_c old, struct bkey_s_c new,
934                             unsigned flags)
935 {
936         u64 journal_seq = trans->journal_res.seq;
937         struct bch_fs *c = trans->c;
938         struct bkey_s_c k = flags & BTREE_TRIGGER_OVERWRITE ? old: new;
939         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
940         const union bch_extent_entry *entry;
941         struct extent_ptr_decoded p;
942         struct bch_replicas_padded r;
943         enum bch_data_type data_type = bkey_is_btree_ptr(k.k)
944                 ? BCH_DATA_btree
945                 : BCH_DATA_user;
946         s64 sectors = bkey_is_btree_ptr(k.k)
947                 ? btree_sectors(c)
948                 : k.k->size;
949         s64 dirty_sectors = 0;
950         bool stale;
951         int ret;
952
953         BUG_ON(!(flags & BTREE_TRIGGER_GC));
954
955         r.e.data_type   = data_type;
956         r.e.nr_devs     = 0;
957         r.e.nr_required = 1;
958
959         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
960                 s64 disk_sectors = ptr_disk_sectors(sectors, p);
961
962                 if (flags & BTREE_TRIGGER_OVERWRITE)
963                         disk_sectors = -disk_sectors;
964
965                 ret = bch2_mark_pointer(trans, k, p, disk_sectors,
966                                         data_type, flags);
967                 if (ret < 0)
968                         return ret;
969
970                 stale = ret > 0;
971
972                 if (p.ptr.cached) {
973                         if (!stale) {
974                                 ret = update_cached_sectors(c, k, p.ptr.dev,
975                                                 disk_sectors, journal_seq, true);
976                                 if (ret) {
977                                         bch2_fs_fatal_error(c, "bch2_mark_extent(): no replicas entry while updating cached sectors");
978                                         return ret;
979                                 }
980                         }
981                 } else if (!p.has_ec) {
982                         dirty_sectors          += disk_sectors;
983                         r.e.devs[r.e.nr_devs++] = p.ptr.dev;
984                 } else {
985                         ret = bch2_mark_stripe_ptr(trans, k, p.ec, data_type,
986                                         disk_sectors, flags);
987                         if (ret)
988                                 return ret;
989
990                         /*
991                          * There may be other dirty pointers in this extent, but
992                          * if so they're not required for mounting if we have an
993                          * erasure coded pointer in this extent:
994                          */
995                         r.e.nr_required = 0;
996                 }
997         }
998
999         if (r.e.nr_devs) {
1000                 ret = update_replicas(c, k, &r.e, dirty_sectors, journal_seq, true);
1001                 if (ret) {
1002                         struct printbuf buf = PRINTBUF;
1003
1004                         bch2_bkey_val_to_text(&buf, c, k);
1005                         bch2_fs_fatal_error(c, "no replicas entry for %s", buf.buf);
1006                         printbuf_exit(&buf);
1007                         return ret;
1008                 }
1009         }
1010
1011         return 0;
1012 }
1013
1014 static int bch2_mark_stripe(struct btree_trans *trans,
1015                             struct bkey_s_c old, struct bkey_s_c new,
1016                             unsigned flags)
1017 {
1018         bool gc = flags & BTREE_TRIGGER_GC;
1019         u64 journal_seq = trans->journal_res.seq;
1020         struct bch_fs *c = trans->c;
1021         u64 idx = new.k->p.offset;
1022         const struct bch_stripe *old_s = old.k->type == KEY_TYPE_stripe
1023                 ? bkey_s_c_to_stripe(old).v : NULL;
1024         const struct bch_stripe *new_s = new.k->type == KEY_TYPE_stripe
1025                 ? bkey_s_c_to_stripe(new).v : NULL;
1026         unsigned i;
1027         int ret;
1028
1029         BUG_ON(gc && old_s);
1030
1031         if (!gc) {
1032                 struct stripe *m = genradix_ptr(&c->stripes, idx);
1033
1034                 if (!m || (old_s && !m->alive)) {
1035                         struct printbuf buf1 = PRINTBUF;
1036                         struct printbuf buf2 = PRINTBUF;
1037
1038                         bch2_bkey_val_to_text(&buf1, c, old);
1039                         bch2_bkey_val_to_text(&buf2, c, new);
1040                         bch_err_ratelimited(c, "error marking nonexistent stripe %llu while marking\n"
1041                                             "old %s\n"
1042                                             "new %s", idx, buf1.buf, buf2.buf);
1043                         printbuf_exit(&buf2);
1044                         printbuf_exit(&buf1);
1045                         bch2_inconsistent_error(c);
1046                         return -1;
1047                 }
1048
1049                 if (!new_s) {
1050                         spin_lock(&c->ec_stripes_heap_lock);
1051                         bch2_stripes_heap_del(c, m, idx);
1052                         spin_unlock(&c->ec_stripes_heap_lock);
1053
1054                         memset(m, 0, sizeof(*m));
1055                 } else {
1056                         m->alive        = true;
1057                         m->sectors      = le16_to_cpu(new_s->sectors);
1058                         m->algorithm    = new_s->algorithm;
1059                         m->nr_blocks    = new_s->nr_blocks;
1060                         m->nr_redundant = new_s->nr_redundant;
1061                         m->blocks_nonempty = 0;
1062
1063                         for (i = 0; i < new_s->nr_blocks; i++)
1064                                 m->blocks_nonempty += !!stripe_blockcount_get(new_s, i);
1065
1066                         spin_lock(&c->ec_stripes_heap_lock);
1067                         bch2_stripes_heap_update(c, m, idx);
1068                         spin_unlock(&c->ec_stripes_heap_lock);
1069                 }
1070         } else {
1071                 struct gc_stripe *m =
1072                         genradix_ptr_alloc(&c->gc_stripes, idx, GFP_KERNEL);
1073
1074                 if (!m) {
1075                         bch_err(c, "error allocating memory for gc_stripes, idx %llu",
1076                                 idx);
1077                         return -ENOMEM;
1078                 }
1079                 /*
1080                  * This will be wrong when we bring back runtime gc: we should
1081                  * be unmarking the old key and then marking the new key
1082                  */
1083                 m->alive        = true;
1084                 m->sectors      = le16_to_cpu(new_s->sectors);
1085                 m->nr_blocks    = new_s->nr_blocks;
1086                 m->nr_redundant = new_s->nr_redundant;
1087
1088                 for (i = 0; i < new_s->nr_blocks; i++)
1089                         m->ptrs[i] = new_s->ptrs[i];
1090
1091                 bch2_bkey_to_replicas(&m->r.e, new);
1092
1093                 /*
1094                  * gc recalculates this field from stripe ptr
1095                  * references:
1096                  */
1097                 memset(m->block_sectors, 0, sizeof(m->block_sectors));
1098
1099                 for (i = 0; i < new_s->nr_blocks; i++) {
1100                         ret = mark_stripe_bucket(trans, new, i, flags);
1101                         if (ret)
1102                                 return ret;
1103                 }
1104
1105                 ret = update_replicas(c, new, &m->r.e,
1106                                       ((s64) m->sectors * m->nr_redundant),
1107                                       journal_seq, gc);
1108                 if (ret) {
1109                         struct printbuf buf = PRINTBUF;
1110
1111                         bch2_bkey_val_to_text(&buf, c, new);
1112                         bch2_fs_fatal_error(c, "no replicas entry for %s", buf.buf);
1113                         printbuf_exit(&buf);
1114                         return ret;
1115                 }
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int bch2_mark_inode(struct btree_trans *trans,
1122                            struct bkey_s_c old, struct bkey_s_c new,
1123                            unsigned flags)
1124 {
1125         struct bch_fs *c = trans->c;
1126         struct bch_fs_usage __percpu *fs_usage;
1127         u64 journal_seq = trans->journal_res.seq;
1128
1129         if (flags & BTREE_TRIGGER_INSERT) {
1130                 struct bch_inode_v2 *v = (struct bch_inode_v2 *) new.v;
1131
1132                 BUG_ON(!journal_seq);
1133                 BUG_ON(new.k->type != KEY_TYPE_inode_v2);
1134
1135                 v->bi_journal_seq = cpu_to_le64(journal_seq);
1136         }
1137
1138         if (flags & BTREE_TRIGGER_GC) {
1139                 percpu_down_read(&c->mark_lock);
1140                 preempt_disable();
1141
1142                 fs_usage = fs_usage_ptr(c, journal_seq, flags & BTREE_TRIGGER_GC);
1143                 fs_usage->nr_inodes += bkey_is_inode(new.k);
1144                 fs_usage->nr_inodes -= bkey_is_inode(old.k);
1145
1146                 preempt_enable();
1147                 percpu_up_read(&c->mark_lock);
1148         }
1149         return 0;
1150 }
1151
1152 static int bch2_mark_reservation(struct btree_trans *trans,
1153                                  struct bkey_s_c old, struct bkey_s_c new,
1154                                  unsigned flags)
1155 {
1156         struct bch_fs *c = trans->c;
1157         struct bkey_s_c k = flags & BTREE_TRIGGER_OVERWRITE ? old: new;
1158         struct bch_fs_usage __percpu *fs_usage;
1159         unsigned replicas = bkey_s_c_to_reservation(k).v->nr_replicas;
1160         s64 sectors = (s64) k.k->size;
1161
1162         BUG_ON(!(flags & BTREE_TRIGGER_GC));
1163
1164         if (flags & BTREE_TRIGGER_OVERWRITE)
1165                 sectors = -sectors;
1166         sectors *= replicas;
1167
1168         percpu_down_read(&c->mark_lock);
1169         preempt_disable();
1170
1171         fs_usage = fs_usage_ptr(c, trans->journal_res.seq, flags & BTREE_TRIGGER_GC);
1172         replicas = clamp_t(unsigned, replicas, 1,
1173                            ARRAY_SIZE(fs_usage->persistent_reserved));
1174
1175         fs_usage->reserved                              += sectors;
1176         fs_usage->persistent_reserved[replicas - 1]     += sectors;
1177
1178         preempt_enable();
1179         percpu_up_read(&c->mark_lock);
1180
1181         return 0;
1182 }
1183
1184 static s64 __bch2_mark_reflink_p(struct btree_trans *trans,
1185                                  struct bkey_s_c_reflink_p p,
1186                                  u64 start, u64 end,
1187                                  u64 *idx, unsigned flags, size_t r_idx)
1188 {
1189         struct bch_fs *c = trans->c;
1190         struct reflink_gc *r;
1191         int add = !(flags & BTREE_TRIGGER_OVERWRITE) ? 1 : -1;
1192         u64 next_idx = end;
1193         s64 ret = 0;
1194         struct printbuf buf = PRINTBUF;
1195
1196         if (r_idx >= c->reflink_gc_nr)
1197                 goto not_found;
1198
1199         r = genradix_ptr(&c->reflink_gc_table, r_idx);
1200         next_idx = min(next_idx, r->offset - r->size);
1201         if (*idx < next_idx)
1202                 goto not_found;
1203
1204         BUG_ON((s64) r->refcount + add < 0);
1205
1206         r->refcount += add;
1207         *idx = r->offset;
1208         return 0;
1209 not_found:
1210         if (fsck_err(c, "pointer to missing indirect extent\n"
1211                      "  %s\n"
1212                      "  missing range %llu-%llu",
1213                      (bch2_bkey_val_to_text(&buf, c, p.s_c), buf.buf),
1214                      *idx, next_idx)) {
1215                 struct bkey_i_error new;
1216
1217                 bkey_init(&new.k);
1218                 new.k.type      = KEY_TYPE_error;
1219                 new.k.p         = bkey_start_pos(p.k);
1220                 new.k.p.offset += *idx - start;
1221                 bch2_key_resize(&new.k, next_idx - *idx);
1222                 ret = __bch2_btree_insert(trans, BTREE_ID_extents, &new.k_i);
1223         }
1224
1225         *idx = next_idx;
1226 fsck_err:
1227         printbuf_exit(&buf);
1228         return ret;
1229 }
1230
1231 static int bch2_mark_reflink_p(struct btree_trans *trans,
1232                                struct bkey_s_c old, struct bkey_s_c new,
1233                                unsigned flags)
1234 {
1235         struct bch_fs *c = trans->c;
1236         struct bkey_s_c k = flags & BTREE_TRIGGER_OVERWRITE ? old: new;
1237         struct bkey_s_c_reflink_p p = bkey_s_c_to_reflink_p(k);
1238         struct reflink_gc *ref;
1239         size_t l, r, m;
1240         u64 idx = le64_to_cpu(p.v->idx), start = idx;
1241         u64 end = le64_to_cpu(p.v->idx) + p.k->size;
1242         int ret = 0;
1243
1244         BUG_ON(!(flags & BTREE_TRIGGER_GC));
1245
1246         if (c->sb.version >= bcachefs_metadata_version_reflink_p_fix) {
1247                 idx -= le32_to_cpu(p.v->front_pad);
1248                 end += le32_to_cpu(p.v->back_pad);
1249         }
1250
1251         l = 0;
1252         r = c->reflink_gc_nr;
1253         while (l < r) {
1254                 m = l + (r - l) / 2;
1255
1256                 ref = genradix_ptr(&c->reflink_gc_table, m);
1257                 if (ref->offset <= idx)
1258                         l = m + 1;
1259                 else
1260                         r = m;
1261         }
1262
1263         while (idx < end && !ret)
1264                 ret = __bch2_mark_reflink_p(trans, p, start, end,
1265                                             &idx, flags, l++);
1266
1267         return ret;
1268 }
1269
1270 int bch2_mark_key(struct btree_trans *trans,
1271                   struct bkey_s_c old,
1272                   struct bkey_s_c new,
1273                   unsigned flags)
1274 {
1275         struct bkey_s_c k = flags & BTREE_TRIGGER_OVERWRITE ? old: new;
1276
1277         switch (k.k->type) {
1278         case KEY_TYPE_alloc:
1279         case KEY_TYPE_alloc_v2:
1280         case KEY_TYPE_alloc_v3:
1281                 return bch2_mark_alloc(trans, old, new, flags);
1282         case KEY_TYPE_btree_ptr:
1283         case KEY_TYPE_btree_ptr_v2:
1284         case KEY_TYPE_extent:
1285         case KEY_TYPE_reflink_v:
1286                 return bch2_mark_extent(trans, old, new, flags);
1287         case KEY_TYPE_stripe:
1288                 return bch2_mark_stripe(trans, old, new, flags);
1289         case KEY_TYPE_inode:
1290         case KEY_TYPE_inode_v2:
1291                 return bch2_mark_inode(trans, old, new, flags);
1292         case KEY_TYPE_reservation:
1293                 return bch2_mark_reservation(trans, old, new, flags);
1294         case KEY_TYPE_reflink_p:
1295                 return bch2_mark_reflink_p(trans, old, new, flags);
1296         case KEY_TYPE_snapshot:
1297                 return bch2_mark_snapshot(trans, old, new, flags);
1298         default:
1299                 return 0;
1300         }
1301 }
1302
1303 static noinline __cold
1304 void fs_usage_apply_warn(struct btree_trans *trans,
1305                          unsigned disk_res_sectors,
1306                          s64 should_not_have_added)
1307 {
1308         struct bch_fs *c = trans->c;
1309         struct btree_insert_entry *i;
1310         struct printbuf buf = PRINTBUF;
1311
1312         bch_err(c, "disk usage increased %lli more than %u sectors reserved",
1313                 should_not_have_added, disk_res_sectors);
1314
1315         trans_for_each_update(trans, i) {
1316                 struct bkey_s_c old = { &i->old_k, i->old_v };
1317
1318                 pr_err("while inserting");
1319                 printbuf_reset(&buf);
1320                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(i->k));
1321                 pr_err("  %s", buf.buf);
1322                 pr_err("overlapping with");
1323                 printbuf_reset(&buf);
1324                 bch2_bkey_val_to_text(&buf, c, old);
1325                 pr_err("  %s", buf.buf);
1326         }
1327
1328         __WARN();
1329         printbuf_exit(&buf);
1330 }
1331
1332 int bch2_trans_fs_usage_apply(struct btree_trans *trans,
1333                               struct replicas_delta_list *deltas)
1334 {
1335         struct bch_fs *c = trans->c;
1336         static int warned_disk_usage = 0;
1337         bool warn = false;
1338         unsigned disk_res_sectors = trans->disk_res ? trans->disk_res->sectors : 0;
1339         struct replicas_delta *d = deltas->d, *d2;
1340         struct replicas_delta *top = (void *) deltas->d + deltas->used;
1341         struct bch_fs_usage *dst;
1342         s64 added = 0, should_not_have_added;
1343         unsigned i;
1344
1345         percpu_down_read(&c->mark_lock);
1346         preempt_disable();
1347         dst = fs_usage_ptr(c, trans->journal_res.seq, false);
1348
1349         for (d = deltas->d; d != top; d = replicas_delta_next(d)) {
1350                 switch (d->r.data_type) {
1351                 case BCH_DATA_btree:
1352                 case BCH_DATA_user:
1353                 case BCH_DATA_parity:
1354                         added += d->delta;
1355                 }
1356
1357                 if (__update_replicas(c, dst, &d->r, d->delta))
1358                         goto need_mark;
1359         }
1360
1361         dst->nr_inodes += deltas->nr_inodes;
1362
1363         for (i = 0; i < BCH_REPLICAS_MAX; i++) {
1364                 added                           += deltas->persistent_reserved[i];
1365                 dst->reserved                   += deltas->persistent_reserved[i];
1366                 dst->persistent_reserved[i]     += deltas->persistent_reserved[i];
1367         }
1368
1369         /*
1370          * Not allowed to reduce sectors_available except by getting a
1371          * reservation:
1372          */
1373         should_not_have_added = added - (s64) disk_res_sectors;
1374         if (unlikely(should_not_have_added > 0)) {
1375                 u64 old, new, v = atomic64_read(&c->sectors_available);
1376
1377                 do {
1378                         old = v;
1379                         new = max_t(s64, 0, old - should_not_have_added);
1380                 } while ((v = atomic64_cmpxchg(&c->sectors_available,
1381                                                old, new)) != old);
1382
1383                 added -= should_not_have_added;
1384                 warn = true;
1385         }
1386
1387         if (added > 0) {
1388                 trans->disk_res->sectors -= added;
1389                 this_cpu_sub(*c->online_reserved, added);
1390         }
1391
1392         preempt_enable();
1393         percpu_up_read(&c->mark_lock);
1394
1395         if (unlikely(warn) && !xchg(&warned_disk_usage, 1))
1396                 fs_usage_apply_warn(trans, disk_res_sectors, should_not_have_added);
1397         return 0;
1398 need_mark:
1399         /* revert changes: */
1400         for (d2 = deltas->d; d2 != d; d2 = replicas_delta_next(d2))
1401                 BUG_ON(__update_replicas(c, dst, &d2->r, -d2->delta));
1402
1403         preempt_enable();
1404         percpu_up_read(&c->mark_lock);
1405         return -1;
1406 }
1407
1408 /* trans_mark: */
1409
1410 static int bch2_trans_start_alloc_update(struct btree_trans *trans, struct btree_iter *iter,
1411                               const struct bch_extent_ptr *ptr,
1412                               struct bkey_alloc_unpacked *u)
1413 {
1414         struct bch_fs *c = trans->c;
1415         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
1416         struct bkey_s_c k;
1417         int ret;
1418
1419         bch2_trans_iter_init(trans, iter, BTREE_ID_alloc,
1420                              POS(ptr->dev, PTR_BUCKET_NR(ca, ptr)),
1421                              BTREE_ITER_WITH_UPDATES|
1422                              BTREE_ITER_CACHED|
1423                              BTREE_ITER_INTENT);
1424         k = bch2_btree_iter_peek_slot(iter);
1425         ret = bkey_err(k);
1426         if (ret) {
1427                 bch2_trans_iter_exit(trans, iter);
1428                 return ret;
1429         }
1430
1431         *u = bch2_alloc_unpack(k);
1432         return 0;
1433 }
1434
1435 static int bch2_trans_mark_pointer(struct btree_trans *trans,
1436                         struct bkey_s_c k, struct extent_ptr_decoded p,
1437                         s64 sectors, enum bch_data_type data_type)
1438 {
1439         struct btree_iter iter;
1440         struct bkey_alloc_unpacked u;
1441         int ret;
1442
1443         ret = bch2_trans_start_alloc_update(trans, &iter, &p.ptr, &u);
1444         if (ret)
1445                 return ret;
1446
1447         ret = __mark_pointer(trans, k, &p.ptr, sectors, data_type,
1448                              u.gen, &u.data_type,
1449                              &u.dirty_sectors, &u.cached_sectors);
1450         if (ret)
1451                 goto out;
1452
1453         ret = bch2_alloc_write(trans, &iter, &u, 0);
1454         if (ret)
1455                 goto out;
1456 out:
1457         bch2_trans_iter_exit(trans, &iter);
1458         return ret;
1459 }
1460
1461 static int bch2_trans_mark_stripe_ptr(struct btree_trans *trans,
1462                         struct extent_ptr_decoded p,
1463                         s64 sectors, enum bch_data_type data_type)
1464 {
1465         struct bch_fs *c = trans->c;
1466         struct btree_iter iter;
1467         struct bkey_s_c k;
1468         struct bkey_i_stripe *s;
1469         struct bch_replicas_padded r;
1470         int ret = 0;
1471
1472         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes, POS(0, p.ec.idx),
1473                              BTREE_ITER_INTENT|
1474                              BTREE_ITER_WITH_UPDATES);
1475         k = bch2_btree_iter_peek_slot(&iter);
1476         ret = bkey_err(k);
1477         if (ret)
1478                 goto err;
1479
1480         if (k.k->type != KEY_TYPE_stripe) {
1481                 bch2_fs_inconsistent(c,
1482                         "pointer to nonexistent stripe %llu",
1483                         (u64) p.ec.idx);
1484                 bch2_inconsistent_error(c);
1485                 ret = -EIO;
1486                 goto err;
1487         }
1488
1489         if (!bch2_ptr_matches_stripe(bkey_s_c_to_stripe(k).v, p)) {
1490                 bch2_fs_inconsistent(c,
1491                         "stripe pointer doesn't match stripe %llu",
1492                         (u64) p.ec.idx);
1493                 ret = -EIO;
1494                 goto err;
1495         }
1496
1497         s = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1498         ret = PTR_ERR_OR_ZERO(s);
1499         if (ret)
1500                 goto err;
1501
1502         bkey_reassemble(&s->k_i, k);
1503         stripe_blockcount_set(&s->v, p.ec.block,
1504                 stripe_blockcount_get(&s->v, p.ec.block) +
1505                 sectors);
1506
1507         ret = bch2_trans_update(trans, &iter, &s->k_i, 0);
1508         if (ret)
1509                 goto err;
1510
1511         bch2_bkey_to_replicas(&r.e, bkey_i_to_s_c(&s->k_i));
1512         r.e.data_type = data_type;
1513         update_replicas_list(trans, &r.e, sectors);
1514 err:
1515         bch2_trans_iter_exit(trans, &iter);
1516         return ret;
1517 }
1518
1519 static int bch2_trans_mark_extent(struct btree_trans *trans,
1520                         struct bkey_s_c k, unsigned flags)
1521 {
1522         struct bch_fs *c = trans->c;
1523         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1524         const union bch_extent_entry *entry;
1525         struct extent_ptr_decoded p;
1526         struct bch_replicas_padded r;
1527         enum bch_data_type data_type = bkey_is_btree_ptr(k.k)
1528                 ? BCH_DATA_btree
1529                 : BCH_DATA_user;
1530         s64 sectors = bkey_is_btree_ptr(k.k)
1531                 ? btree_sectors(c)
1532                 : k.k->size;
1533         s64 dirty_sectors = 0;
1534         bool stale;
1535         int ret;
1536
1537         r.e.data_type   = data_type;
1538         r.e.nr_devs     = 0;
1539         r.e.nr_required = 1;
1540
1541         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
1542                 s64 disk_sectors = ptr_disk_sectors(sectors, p);
1543
1544                 if (flags & BTREE_TRIGGER_OVERWRITE)
1545                         disk_sectors = -disk_sectors;
1546
1547                 ret = bch2_trans_mark_pointer(trans, k, p,
1548                                         disk_sectors, data_type);
1549                 if (ret < 0)
1550                         return ret;
1551
1552                 stale = ret > 0;
1553
1554                 if (p.ptr.cached) {
1555                         if (!stale)
1556                                 update_cached_sectors_list(trans, p.ptr.dev,
1557                                                            disk_sectors);
1558                 } else if (!p.has_ec) {
1559                         dirty_sectors          += disk_sectors;
1560                         r.e.devs[r.e.nr_devs++] = p.ptr.dev;
1561                 } else {
1562                         ret = bch2_trans_mark_stripe_ptr(trans, p,
1563                                         disk_sectors, data_type);
1564                         if (ret)
1565                                 return ret;
1566
1567                         r.e.nr_required = 0;
1568                 }
1569         }
1570
1571         if (r.e.nr_devs)
1572                 update_replicas_list(trans, &r.e, dirty_sectors);
1573
1574         return 0;
1575 }
1576
1577 static int bch2_trans_mark_stripe_bucket(struct btree_trans *trans,
1578                                          struct bkey_s_c_stripe s,
1579                                          unsigned idx, bool deleting)
1580 {
1581         struct bch_fs *c = trans->c;
1582         const struct bch_extent_ptr *ptr = &s.v->ptrs[idx];
1583         struct btree_iter iter;
1584         struct bkey_alloc_unpacked u;
1585         enum bch_data_type data_type = idx >= s.v->nr_blocks - s.v->nr_redundant
1586                 ? BCH_DATA_parity : 0;
1587         s64 sectors = data_type ? le16_to_cpu(s.v->sectors) : 0;
1588         int ret = 0;
1589
1590         if (deleting)
1591                 sectors = -sectors;
1592
1593         ret = bch2_trans_start_alloc_update(trans, &iter, ptr, &u);
1594         if (ret)
1595                 return ret;
1596
1597         ret = check_bucket_ref(c, s.s_c, ptr, sectors, data_type,
1598                                u.gen, u.data_type,
1599                                u.dirty_sectors, u.cached_sectors);
1600         if (ret)
1601                 goto err;
1602
1603         if (!deleting) {
1604                 if (bch2_fs_inconsistent_on(u.stripe ||
1605                                             u.stripe_redundancy, c,
1606                                 "bucket %llu:%llu gen %u data type %s dirty_sectors %u: multiple stripes using same bucket (%u, %llu)",
1607                                 iter.pos.inode, iter.pos.offset, u.gen,
1608                                 bch2_data_types[u.data_type],
1609                                 u.dirty_sectors,
1610                                 u.stripe, s.k->p.offset)) {
1611                         ret = -EIO;
1612                         goto err;
1613                 }
1614
1615                 if (bch2_fs_inconsistent_on(data_type && u.dirty_sectors, c,
1616                                 "bucket %llu:%llu gen %u data type %s dirty_sectors %u: data already in stripe bucket %llu",
1617                                 iter.pos.inode, iter.pos.offset, u.gen,
1618                                 bch2_data_types[u.data_type],
1619                                 u.dirty_sectors,
1620                                 s.k->p.offset)) {
1621                         ret = -EIO;
1622                         goto err;
1623                 }
1624
1625                 u.stripe                = s.k->p.offset;
1626                 u.stripe_redundancy     = s.v->nr_redundant;
1627         } else {
1628                 if (bch2_fs_inconsistent_on(u.stripe != s.k->p.offset ||
1629                                             u.stripe_redundancy != s.v->nr_redundant, c,
1630                                 "bucket %llu:%llu gen %u: not marked as stripe when deleting stripe %llu (got %u)",
1631                                 iter.pos.inode, iter.pos.offset, u.gen,
1632                                 s.k->p.offset, u.stripe)) {
1633                         ret = -EIO;
1634                         goto err;
1635                 }
1636
1637                 u.stripe                = 0;
1638                 u.stripe_redundancy     = 0;
1639         }
1640
1641         u.dirty_sectors += sectors;
1642         if (data_type)
1643                 u.data_type = !deleting ? data_type : 0;
1644
1645         ret = bch2_alloc_write(trans, &iter, &u, 0);
1646         if (ret)
1647                 goto err;
1648 err:
1649         bch2_trans_iter_exit(trans, &iter);
1650         return ret;
1651 }
1652
1653 static int bch2_trans_mark_stripe(struct btree_trans *trans,
1654                                   struct bkey_s_c old, struct bkey_i *new,
1655                                   unsigned flags)
1656 {
1657         const struct bch_stripe *old_s = NULL;
1658         struct bch_stripe *new_s = NULL;
1659         struct bch_replicas_padded r;
1660         unsigned i, nr_blocks;
1661         int ret = 0;
1662
1663         if (old.k->type == KEY_TYPE_stripe)
1664                 old_s = bkey_s_c_to_stripe(old).v;
1665         if (new->k.type == KEY_TYPE_stripe)
1666                 new_s = &bkey_i_to_stripe(new)->v;
1667
1668         /*
1669          * If the pointers aren't changing, we don't need to do anything:
1670          */
1671         if (new_s && old_s &&
1672             new_s->nr_blocks    == old_s->nr_blocks &&
1673             new_s->nr_redundant == old_s->nr_redundant &&
1674             !memcmp(old_s->ptrs, new_s->ptrs,
1675                     new_s->nr_blocks * sizeof(struct bch_extent_ptr)))
1676                 return 0;
1677
1678         BUG_ON(new_s && old_s &&
1679                (new_s->nr_blocks        != old_s->nr_blocks ||
1680                 new_s->nr_redundant     != old_s->nr_redundant));
1681
1682         nr_blocks = new_s ? new_s->nr_blocks : old_s->nr_blocks;
1683
1684         if (new_s) {
1685                 s64 sectors = le16_to_cpu(new_s->sectors);
1686
1687                 bch2_bkey_to_replicas(&r.e, bkey_i_to_s_c(new));
1688                 update_replicas_list(trans, &r.e, sectors * new_s->nr_redundant);
1689         }
1690
1691         if (old_s) {
1692                 s64 sectors = -((s64) le16_to_cpu(old_s->sectors));
1693
1694                 bch2_bkey_to_replicas(&r.e, old);
1695                 update_replicas_list(trans, &r.e, sectors * old_s->nr_redundant);
1696         }
1697
1698         for (i = 0; i < nr_blocks; i++) {
1699                 if (new_s && old_s &&
1700                     !memcmp(&new_s->ptrs[i],
1701                             &old_s->ptrs[i],
1702                             sizeof(new_s->ptrs[i])))
1703                         continue;
1704
1705                 if (new_s) {
1706                         ret = bch2_trans_mark_stripe_bucket(trans,
1707                                         bkey_i_to_s_c_stripe(new), i, false);
1708                         if (ret)
1709                                 break;
1710                 }
1711
1712                 if (old_s) {
1713                         ret = bch2_trans_mark_stripe_bucket(trans,
1714                                         bkey_s_c_to_stripe(old), i, true);
1715                         if (ret)
1716                                 break;
1717                 }
1718         }
1719
1720         return ret;
1721 }
1722
1723 static int bch2_trans_mark_inode(struct btree_trans *trans,
1724                                  struct bkey_s_c old,
1725                                  struct bkey_i *new,
1726                                  unsigned flags)
1727 {
1728         int nr = bkey_is_inode(&new->k) - bkey_is_inode(old.k);
1729
1730         if (nr) {
1731                 struct replicas_delta_list *d =
1732                         replicas_deltas_realloc(trans, 0);
1733                 d->nr_inodes += nr;
1734         }
1735
1736         return 0;
1737 }
1738
1739 static int bch2_trans_mark_reservation(struct btree_trans *trans,
1740                                        struct bkey_s_c k, unsigned flags)
1741 {
1742         unsigned replicas = bkey_s_c_to_reservation(k).v->nr_replicas;
1743         s64 sectors = (s64) k.k->size;
1744         struct replicas_delta_list *d;
1745
1746         if (flags & BTREE_TRIGGER_OVERWRITE)
1747                 sectors = -sectors;
1748         sectors *= replicas;
1749
1750         d = replicas_deltas_realloc(trans, 0);
1751
1752         replicas = clamp_t(unsigned, replicas, 1,
1753                            ARRAY_SIZE(d->persistent_reserved));
1754
1755         d->persistent_reserved[replicas - 1] += sectors;
1756         return 0;
1757 }
1758
1759 static int __bch2_trans_mark_reflink_p(struct btree_trans *trans,
1760                         struct bkey_s_c_reflink_p p,
1761                         u64 *idx, unsigned flags)
1762 {
1763         struct bch_fs *c = trans->c;
1764         struct btree_iter iter;
1765         struct bkey_s_c k;
1766         struct bkey_i *n;
1767         __le64 *refcount;
1768         int add = !(flags & BTREE_TRIGGER_OVERWRITE) ? 1 : -1;
1769         struct printbuf buf = PRINTBUF;
1770         int ret;
1771
1772         bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink, POS(0, *idx),
1773                              BTREE_ITER_INTENT|
1774                              BTREE_ITER_WITH_UPDATES);
1775         k = bch2_btree_iter_peek_slot(&iter);
1776         ret = bkey_err(k);
1777         if (ret)
1778                 goto err;
1779
1780         n = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1781         ret = PTR_ERR_OR_ZERO(n);
1782         if (ret)
1783                 goto err;
1784
1785         bkey_reassemble(n, k);
1786
1787         refcount = bkey_refcount(n);
1788         if (!refcount) {
1789                 bch2_bkey_val_to_text(&buf, c, p.s_c);
1790                 bch2_fs_inconsistent(c,
1791                         "nonexistent indirect extent at %llu while marking\n  %s",
1792                         *idx, buf.buf);
1793                 ret = -EIO;
1794                 goto err;
1795         }
1796
1797         if (!*refcount && (flags & BTREE_TRIGGER_OVERWRITE)) {
1798                 bch2_bkey_val_to_text(&buf, c, p.s_c);
1799                 bch2_fs_inconsistent(c,
1800                         "indirect extent refcount underflow at %llu while marking\n  %s",
1801                         *idx, buf.buf);
1802                 ret = -EIO;
1803                 goto err;
1804         }
1805
1806         if (flags & BTREE_TRIGGER_INSERT) {
1807                 struct bch_reflink_p *v = (struct bch_reflink_p *) p.v;
1808                 u64 pad;
1809
1810                 pad = max_t(s64, le32_to_cpu(v->front_pad),
1811                             le64_to_cpu(v->idx) - bkey_start_offset(k.k));
1812                 BUG_ON(pad > U32_MAX);
1813                 v->front_pad = cpu_to_le32(pad);
1814
1815                 pad = max_t(s64, le32_to_cpu(v->back_pad),
1816                             k.k->p.offset - p.k->size - le64_to_cpu(v->idx));
1817                 BUG_ON(pad > U32_MAX);
1818                 v->back_pad = cpu_to_le32(pad);
1819         }
1820
1821         le64_add_cpu(refcount, add);
1822
1823         if (!*refcount) {
1824                 n->k.type = KEY_TYPE_deleted;
1825                 set_bkey_val_u64s(&n->k, 0);
1826         }
1827
1828         bch2_btree_iter_set_pos_to_extent_start(&iter);
1829         ret = bch2_trans_update(trans, &iter, n, 0);
1830         if (ret)
1831                 goto err;
1832
1833         *idx = k.k->p.offset;
1834 err:
1835         bch2_trans_iter_exit(trans, &iter);
1836         printbuf_exit(&buf);
1837         return ret;
1838 }
1839
1840 static int bch2_trans_mark_reflink_p(struct btree_trans *trans,
1841                                      struct bkey_s_c k, unsigned flags)
1842 {
1843         struct bkey_s_c_reflink_p p = bkey_s_c_to_reflink_p(k);
1844         u64 idx, end_idx;
1845         int ret = 0;
1846
1847         if (flags & BTREE_TRIGGER_INSERT) {
1848                 struct bch_reflink_p *v = (struct bch_reflink_p *) p.v;
1849
1850                 v->front_pad = v->back_pad = 0;
1851         }
1852
1853         idx     = le64_to_cpu(p.v->idx) - le32_to_cpu(p.v->front_pad);
1854         end_idx = le64_to_cpu(p.v->idx) + p.k->size +
1855                 le32_to_cpu(p.v->back_pad);
1856
1857         while (idx < end_idx && !ret)
1858                 ret = __bch2_trans_mark_reflink_p(trans, p, &idx, flags);
1859
1860         return ret;
1861 }
1862
1863 int bch2_trans_mark_key(struct btree_trans *trans, struct bkey_s_c old,
1864                         struct bkey_i *new, unsigned flags)
1865 {
1866         struct bkey_s_c k = flags & BTREE_TRIGGER_OVERWRITE
1867                 ? old
1868                 : bkey_i_to_s_c(new);
1869
1870         switch (k.k->type) {
1871         case KEY_TYPE_btree_ptr:
1872         case KEY_TYPE_btree_ptr_v2:
1873         case KEY_TYPE_extent:
1874         case KEY_TYPE_reflink_v:
1875                 return bch2_trans_mark_extent(trans, k, flags);
1876         case KEY_TYPE_stripe:
1877                 return bch2_trans_mark_stripe(trans, old, new, flags);
1878         case KEY_TYPE_inode:
1879         case KEY_TYPE_inode_v2:
1880                 return bch2_trans_mark_inode(trans, old, new, flags);
1881         case KEY_TYPE_reservation:
1882                 return bch2_trans_mark_reservation(trans, k, flags);
1883         case KEY_TYPE_reflink_p:
1884                 return bch2_trans_mark_reflink_p(trans, k, flags);
1885         default:
1886                 return 0;
1887         }
1888 }
1889
1890 static int __bch2_trans_mark_metadata_bucket(struct btree_trans *trans,
1891                                     struct bch_dev *ca, size_t b,
1892                                     enum bch_data_type type,
1893                                     unsigned sectors)
1894 {
1895         struct bch_fs *c = trans->c;
1896         struct btree_iter iter;
1897         struct bkey_alloc_unpacked u;
1898         struct bch_extent_ptr ptr = {
1899                 .dev = ca->dev_idx,
1900                 .offset = bucket_to_sector(ca, b),
1901         };
1902         int ret = 0;
1903
1904         /*
1905          * Backup superblock might be past the end of our normal usable space:
1906          */
1907         if (b >= ca->mi.nbuckets)
1908                 return 0;
1909
1910         ret = bch2_trans_start_alloc_update(trans, &iter, &ptr, &u);
1911         if (ret)
1912                 return ret;
1913
1914         if (u.data_type && u.data_type != type) {
1915                 bch2_fsck_err(c, FSCK_CAN_IGNORE|FSCK_NEED_FSCK,
1916                         "bucket %llu:%llu gen %u different types of data in same bucket: %s, %s\n"
1917                         "while marking %s",
1918                         iter.pos.inode, iter.pos.offset, u.gen,
1919                         bch2_data_types[u.data_type],
1920                         bch2_data_types[type],
1921                         bch2_data_types[type]);
1922                 ret = -EIO;
1923                 goto out;
1924         }
1925
1926         u.data_type     = type;
1927         u.dirty_sectors = sectors;
1928
1929         ret = bch2_alloc_write(trans, &iter, &u, 0);
1930         if (ret)
1931                 goto out;
1932 out:
1933         bch2_trans_iter_exit(trans, &iter);
1934         return ret;
1935 }
1936
1937 int bch2_trans_mark_metadata_bucket(struct btree_trans *trans,
1938                                     struct bch_dev *ca, size_t b,
1939                                     enum bch_data_type type,
1940                                     unsigned sectors)
1941 {
1942         return __bch2_trans_do(trans, NULL, NULL, 0,
1943                         __bch2_trans_mark_metadata_bucket(trans, ca, b, type, sectors));
1944 }
1945
1946 static int bch2_trans_mark_metadata_sectors(struct btree_trans *trans,
1947                                             struct bch_dev *ca,
1948                                             u64 start, u64 end,
1949                                             enum bch_data_type type,
1950                                             u64 *bucket, unsigned *bucket_sectors)
1951 {
1952         do {
1953                 u64 b = sector_to_bucket(ca, start);
1954                 unsigned sectors =
1955                         min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
1956
1957                 if (b != *bucket && *bucket_sectors) {
1958                         int ret = bch2_trans_mark_metadata_bucket(trans, ca, *bucket,
1959                                                                   type, *bucket_sectors);
1960                         if (ret)
1961                                 return ret;
1962
1963                         *bucket_sectors = 0;
1964                 }
1965
1966                 *bucket         = b;
1967                 *bucket_sectors += sectors;
1968                 start += sectors;
1969         } while (start < end);
1970
1971         return 0;
1972 }
1973
1974 static int __bch2_trans_mark_dev_sb(struct btree_trans *trans,
1975                                     struct bch_dev *ca)
1976 {
1977         struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
1978         u64 bucket = 0;
1979         unsigned i, bucket_sectors = 0;
1980         int ret;
1981
1982         for (i = 0; i < layout->nr_superblocks; i++) {
1983                 u64 offset = le64_to_cpu(layout->sb_offset[i]);
1984
1985                 if (offset == BCH_SB_SECTOR) {
1986                         ret = bch2_trans_mark_metadata_sectors(trans, ca,
1987                                                 0, BCH_SB_SECTOR,
1988                                                 BCH_DATA_sb, &bucket, &bucket_sectors);
1989                         if (ret)
1990                                 return ret;
1991                 }
1992
1993                 ret = bch2_trans_mark_metadata_sectors(trans, ca, offset,
1994                                       offset + (1 << layout->sb_max_size_bits),
1995                                       BCH_DATA_sb, &bucket, &bucket_sectors);
1996                 if (ret)
1997                         return ret;
1998         }
1999
2000         if (bucket_sectors) {
2001                 ret = bch2_trans_mark_metadata_bucket(trans, ca,
2002                                 bucket, BCH_DATA_sb, bucket_sectors);
2003                 if (ret)
2004                         return ret;
2005         }
2006
2007         for (i = 0; i < ca->journal.nr; i++) {
2008                 ret = bch2_trans_mark_metadata_bucket(trans, ca,
2009                                 ca->journal.buckets[i],
2010                                 BCH_DATA_journal, ca->mi.bucket_size);
2011                 if (ret)
2012                         return ret;
2013         }
2014
2015         return 0;
2016 }
2017
2018 int bch2_trans_mark_dev_sb(struct bch_fs *c, struct bch_dev *ca)
2019 {
2020         return bch2_trans_do(c, NULL, NULL, BTREE_INSERT_LAZY_RW,
2021                         __bch2_trans_mark_dev_sb(&trans, ca));
2022 }
2023
2024 /* Disk reservations: */
2025
2026 #define SECTORS_CACHE   1024
2027
2028 int bch2_disk_reservation_add(struct bch_fs *c, struct disk_reservation *res,
2029                               u64 sectors, int flags)
2030 {
2031         struct bch_fs_pcpu *pcpu;
2032         u64 old, v, get;
2033         s64 sectors_available;
2034         int ret;
2035
2036         percpu_down_read(&c->mark_lock);
2037         preempt_disable();
2038         pcpu = this_cpu_ptr(c->pcpu);
2039
2040         if (sectors <= pcpu->sectors_available)
2041                 goto out;
2042
2043         v = atomic64_read(&c->sectors_available);
2044         do {
2045                 old = v;
2046                 get = min((u64) sectors + SECTORS_CACHE, old);
2047
2048                 if (get < sectors) {
2049                         preempt_enable();
2050                         goto recalculate;
2051                 }
2052         } while ((v = atomic64_cmpxchg(&c->sectors_available,
2053                                        old, old - get)) != old);
2054
2055         pcpu->sectors_available         += get;
2056
2057 out:
2058         pcpu->sectors_available         -= sectors;
2059         this_cpu_add(*c->online_reserved, sectors);
2060         res->sectors                    += sectors;
2061
2062         preempt_enable();
2063         percpu_up_read(&c->mark_lock);
2064         return 0;
2065
2066 recalculate:
2067         mutex_lock(&c->sectors_available_lock);
2068
2069         percpu_u64_set(&c->pcpu->sectors_available, 0);
2070         sectors_available = avail_factor(__bch2_fs_usage_read_short(c).free);
2071
2072         if (sectors <= sectors_available ||
2073             (flags & BCH_DISK_RESERVATION_NOFAIL)) {
2074                 atomic64_set(&c->sectors_available,
2075                              max_t(s64, 0, sectors_available - sectors));
2076                 this_cpu_add(*c->online_reserved, sectors);
2077                 res->sectors                    += sectors;
2078                 ret = 0;
2079         } else {
2080                 atomic64_set(&c->sectors_available, sectors_available);
2081                 ret = -ENOSPC;
2082         }
2083
2084         mutex_unlock(&c->sectors_available_lock);
2085         percpu_up_read(&c->mark_lock);
2086
2087         return ret;
2088 }
2089
2090 /* Startup/shutdown: */
2091
2092 static void buckets_free_rcu(struct rcu_head *rcu)
2093 {
2094         struct bucket_array *buckets =
2095                 container_of(rcu, struct bucket_array, rcu);
2096
2097         kvpfree(buckets,
2098                 sizeof(*buckets) +
2099                 buckets->nbuckets * sizeof(struct bucket));
2100 }
2101
2102 static void bucket_gens_free_rcu(struct rcu_head *rcu)
2103 {
2104         struct bucket_gens *buckets =
2105                 container_of(rcu, struct bucket_gens, rcu);
2106
2107         kvpfree(buckets, sizeof(*buckets) + buckets->nbuckets);
2108 }
2109
2110 int bch2_dev_buckets_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets)
2111 {
2112         struct bucket_array *buckets = NULL, *old_buckets = NULL;
2113         struct bucket_gens *bucket_gens = NULL, *old_bucket_gens = NULL;
2114         unsigned long *buckets_nouse = NULL;
2115         alloc_fifo      free[RESERVE_NR];
2116         alloc_fifo      free_inc;
2117         alloc_heap      alloc_heap;
2118
2119         size_t btree_reserve    = DIV_ROUND_UP(BTREE_NODE_RESERVE,
2120                              ca->mi.bucket_size / btree_sectors(c));
2121         /* XXX: these should be tunable */
2122         size_t reserve_none     = max_t(size_t, 1, nbuckets >> 9);
2123         size_t copygc_reserve   = max_t(size_t, 2, nbuckets >> 6);
2124         size_t free_inc_nr      = max(max_t(size_t, 1, nbuckets >> 12),
2125                                       btree_reserve * 2);
2126         bool resize = ca->buckets[0] != NULL;
2127         int ret = -ENOMEM;
2128         unsigned i;
2129
2130         memset(&free,           0, sizeof(free));
2131         memset(&free_inc,       0, sizeof(free_inc));
2132         memset(&alloc_heap,     0, sizeof(alloc_heap));
2133
2134         if (!(buckets           = kvpmalloc(sizeof(struct bucket_array) +
2135                                             nbuckets * sizeof(struct bucket),
2136                                             GFP_KERNEL|__GFP_ZERO)) ||
2137             !(bucket_gens       = kvpmalloc(sizeof(struct bucket_gens) + nbuckets,
2138                                             GFP_KERNEL|__GFP_ZERO)) ||
2139             (c->opts.buckets_nouse &&
2140              !(buckets_nouse    = kvpmalloc(BITS_TO_LONGS(nbuckets) *
2141                                             sizeof(unsigned long),
2142                                             GFP_KERNEL|__GFP_ZERO))) ||
2143             !init_fifo(&free[RESERVE_MOVINGGC],
2144                        copygc_reserve, GFP_KERNEL) ||
2145             !init_fifo(&free[RESERVE_NONE], reserve_none, GFP_KERNEL) ||
2146             !init_fifo(&free_inc,       free_inc_nr, GFP_KERNEL) ||
2147             !init_heap(&alloc_heap,     ALLOC_SCAN_BATCH(ca) << 1, GFP_KERNEL))
2148                 goto err;
2149
2150         buckets->first_bucket   = ca->mi.first_bucket;
2151         buckets->nbuckets       = nbuckets;
2152         bucket_gens->first_bucket = ca->mi.first_bucket;
2153         bucket_gens->nbuckets   = nbuckets;
2154
2155         bch2_copygc_stop(c);
2156
2157         if (resize) {
2158                 down_write(&c->gc_lock);
2159                 down_write(&ca->bucket_lock);
2160                 percpu_down_write(&c->mark_lock);
2161         }
2162
2163         old_buckets = bucket_array(ca);
2164         old_bucket_gens = rcu_dereference_protected(ca->bucket_gens, 1);
2165
2166         if (resize) {
2167                 size_t n = min(buckets->nbuckets, old_buckets->nbuckets);
2168
2169                 memcpy(buckets->b,
2170                        old_buckets->b,
2171                        n * sizeof(struct bucket));
2172                 memcpy(bucket_gens->b,
2173                        old_bucket_gens->b,
2174                        n);
2175                 if (buckets_nouse)
2176                         memcpy(buckets_nouse,
2177                                ca->buckets_nouse,
2178                                BITS_TO_LONGS(n) * sizeof(unsigned long));
2179         }
2180
2181         rcu_assign_pointer(ca->buckets[0], buckets);
2182         rcu_assign_pointer(ca->bucket_gens, bucket_gens);
2183         buckets         = old_buckets;
2184         bucket_gens     = old_bucket_gens;
2185
2186         swap(ca->buckets_nouse, buckets_nouse);
2187
2188         if (resize) {
2189                 percpu_up_write(&c->mark_lock);
2190                 up_write(&c->gc_lock);
2191         }
2192
2193         spin_lock(&c->freelist_lock);
2194         for (i = 0; i < RESERVE_NR; i++) {
2195                 fifo_move(&free[i], &ca->free[i]);
2196                 swap(ca->free[i], free[i]);
2197         }
2198         fifo_move(&free_inc, &ca->free_inc);
2199         swap(ca->free_inc, free_inc);
2200         spin_unlock(&c->freelist_lock);
2201
2202         /* with gc lock held, alloc_heap can't be in use: */
2203         swap(ca->alloc_heap, alloc_heap);
2204
2205         nbuckets = ca->mi.nbuckets;
2206
2207         if (resize)
2208                 up_write(&ca->bucket_lock);
2209
2210         ret = 0;
2211 err:
2212         free_heap(&alloc_heap);
2213         free_fifo(&free_inc);
2214         for (i = 0; i < RESERVE_NR; i++)
2215                 free_fifo(&free[i]);
2216         kvpfree(buckets_nouse,
2217                 BITS_TO_LONGS(nbuckets) * sizeof(unsigned long));
2218         if (bucket_gens)
2219                 call_rcu(&bucket_gens->rcu, bucket_gens_free_rcu);
2220         if (buckets)
2221                 call_rcu(&buckets->rcu, buckets_free_rcu);
2222
2223         return ret;
2224 }
2225
2226 void bch2_dev_buckets_free(struct bch_dev *ca)
2227 {
2228         unsigned i;
2229
2230         free_heap(&ca->alloc_heap);
2231         free_fifo(&ca->free_inc);
2232         for (i = 0; i < RESERVE_NR; i++)
2233                 free_fifo(&ca->free[i]);
2234         kvpfree(ca->buckets_nouse,
2235                 BITS_TO_LONGS(ca->mi.nbuckets) * sizeof(unsigned long));
2236         kvpfree(rcu_dereference_protected(ca->bucket_gens, 1),
2237                 sizeof(struct bucket_gens) + ca->mi.nbuckets);
2238         kvpfree(rcu_dereference_protected(ca->buckets[0], 1),
2239                 sizeof(struct bucket_array) +
2240                 ca->mi.nbuckets * sizeof(struct bucket));
2241
2242         for (i = 0; i < ARRAY_SIZE(ca->usage); i++)
2243                 free_percpu(ca->usage[i]);
2244         kfree(ca->usage_base);
2245 }
2246
2247 int bch2_dev_buckets_alloc(struct bch_fs *c, struct bch_dev *ca)
2248 {
2249         unsigned i;
2250
2251         ca->usage_base = kzalloc(sizeof(struct bch_dev_usage), GFP_KERNEL);
2252         if (!ca->usage_base)
2253                 return -ENOMEM;
2254
2255         for (i = 0; i < ARRAY_SIZE(ca->usage); i++) {
2256                 ca->usage[i] = alloc_percpu(struct bch_dev_usage);
2257                 if (!ca->usage[i])
2258                         return -ENOMEM;
2259         }
2260
2261         return bch2_dev_buckets_resize(c, ca, ca->mi.nbuckets);;
2262 }