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