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