]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to 8d3fc97ca3 bcachefs: Fixes for building in userspace
[bcachefs-tools-debian] / libbcachefs / alloc_background.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "alloc_background.h"
4 #include "alloc_foreground.h"
5 #include "backpointers.h"
6 #include "btree_cache.h"
7 #include "btree_io.h"
8 #include "btree_key_cache.h"
9 #include "btree_update.h"
10 #include "btree_update_interior.h"
11 #include "btree_gc.h"
12 #include "buckets.h"
13 #include "buckets_waiting_for_journal.h"
14 #include "clock.h"
15 #include "debug.h"
16 #include "ec.h"
17 #include "error.h"
18 #include "lru.h"
19 #include "recovery.h"
20 #include "varint.h"
21
22 #include <linux/kthread.h>
23 #include <linux/math64.h>
24 #include <linux/random.h>
25 #include <linux/rculist.h>
26 #include <linux/rcupdate.h>
27 #include <linux/sched/task.h>
28 #include <linux/sort.h>
29 #include <trace/events/bcachefs.h>
30
31 /* Persistent alloc info: */
32
33 static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
34 #define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
35         BCH_ALLOC_FIELDS_V1()
36 #undef x
37 };
38
39 struct bkey_alloc_unpacked {
40         u64             journal_seq;
41         u8              gen;
42         u8              oldest_gen;
43         u8              data_type;
44         bool            need_discard:1;
45         bool            need_inc_gen:1;
46 #define x(_name, _bits) u##_bits _name;
47         BCH_ALLOC_FIELDS_V2()
48 #undef  x
49 };
50
51 static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
52                                      const void **p, unsigned field)
53 {
54         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
55         u64 v;
56
57         if (!(a->fields & (1 << field)))
58                 return 0;
59
60         switch (bytes) {
61         case 1:
62                 v = *((const u8 *) *p);
63                 break;
64         case 2:
65                 v = le16_to_cpup(*p);
66                 break;
67         case 4:
68                 v = le32_to_cpup(*p);
69                 break;
70         case 8:
71                 v = le64_to_cpup(*p);
72                 break;
73         default:
74                 BUG();
75         }
76
77         *p += bytes;
78         return v;
79 }
80
81 static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
82                                       unsigned field, u64 v)
83 {
84         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
85
86         if (!v)
87                 return;
88
89         a->v.fields |= 1 << field;
90
91         switch (bytes) {
92         case 1:
93                 *((u8 *) *p) = v;
94                 break;
95         case 2:
96                 *((__le16 *) *p) = cpu_to_le16(v);
97                 break;
98         case 4:
99                 *((__le32 *) *p) = cpu_to_le32(v);
100                 break;
101         case 8:
102                 *((__le64 *) *p) = cpu_to_le64(v);
103                 break;
104         default:
105                 BUG();
106         }
107
108         *p += bytes;
109 }
110
111 static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
112                                  struct bkey_s_c k)
113 {
114         const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
115         const void *d = in->data;
116         unsigned idx = 0;
117
118         out->gen = in->gen;
119
120 #define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
121         BCH_ALLOC_FIELDS_V1()
122 #undef  x
123 }
124
125 static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
126                                 struct bkey_s_c k)
127 {
128         struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
129         const u8 *in = a.v->data;
130         const u8 *end = bkey_val_end(a);
131         unsigned fieldnr = 0;
132         int ret;
133         u64 v;
134
135         out->gen        = a.v->gen;
136         out->oldest_gen = a.v->oldest_gen;
137         out->data_type  = a.v->data_type;
138
139 #define x(_name, _bits)                                                 \
140         if (fieldnr < a.v->nr_fields) {                                 \
141                 ret = bch2_varint_decode_fast(in, end, &v);             \
142                 if (ret < 0)                                            \
143                         return ret;                                     \
144                 in += ret;                                              \
145         } else {                                                        \
146                 v = 0;                                                  \
147         }                                                               \
148         out->_name = v;                                                 \
149         if (v != out->_name)                                            \
150                 return -1;                                              \
151         fieldnr++;
152
153         BCH_ALLOC_FIELDS_V2()
154 #undef  x
155         return 0;
156 }
157
158 static int bch2_alloc_unpack_v3(struct bkey_alloc_unpacked *out,
159                                 struct bkey_s_c k)
160 {
161         struct bkey_s_c_alloc_v3 a = bkey_s_c_to_alloc_v3(k);
162         const u8 *in = a.v->data;
163         const u8 *end = bkey_val_end(a);
164         unsigned fieldnr = 0;
165         int ret;
166         u64 v;
167
168         out->gen        = a.v->gen;
169         out->oldest_gen = a.v->oldest_gen;
170         out->data_type  = a.v->data_type;
171         out->need_discard = BCH_ALLOC_V3_NEED_DISCARD(a.v);
172         out->need_inc_gen = BCH_ALLOC_V3_NEED_INC_GEN(a.v);
173         out->journal_seq = le64_to_cpu(a.v->journal_seq);
174
175 #define x(_name, _bits)                                                 \
176         if (fieldnr < a.v->nr_fields) {                                 \
177                 ret = bch2_varint_decode_fast(in, end, &v);             \
178                 if (ret < 0)                                            \
179                         return ret;                                     \
180                 in += ret;                                              \
181         } else {                                                        \
182                 v = 0;                                                  \
183         }                                                               \
184         out->_name = v;                                                 \
185         if (v != out->_name)                                            \
186                 return -1;                                              \
187         fieldnr++;
188
189         BCH_ALLOC_FIELDS_V2()
190 #undef  x
191         return 0;
192 }
193
194 static struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
195 {
196         struct bkey_alloc_unpacked ret = { .gen = 0 };
197
198         switch (k.k->type) {
199         case KEY_TYPE_alloc:
200                 bch2_alloc_unpack_v1(&ret, k);
201                 break;
202         case KEY_TYPE_alloc_v2:
203                 bch2_alloc_unpack_v2(&ret, k);
204                 break;
205         case KEY_TYPE_alloc_v3:
206                 bch2_alloc_unpack_v3(&ret, k);
207                 break;
208         }
209
210         return ret;
211 }
212
213 static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
214 {
215         unsigned i, bytes = offsetof(struct bch_alloc, data);
216
217         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
218                 if (a->fields & (1 << i))
219                         bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
220
221         return DIV_ROUND_UP(bytes, sizeof(u64));
222 }
223
224 int bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k,
225                           int rw, struct printbuf *err)
226 {
227         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
228
229         /* allow for unknown fields */
230         if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v)) {
231                 prt_printf(err, "incorrect value size (%zu < %u)",
232                        bkey_val_u64s(a.k), bch_alloc_v1_val_u64s(a.v));
233                 return -EINVAL;
234         }
235
236         return 0;
237 }
238
239 int bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k,
240                           int rw, struct printbuf *err)
241 {
242         struct bkey_alloc_unpacked u;
243
244         if (bch2_alloc_unpack_v2(&u, k)) {
245                 prt_printf(err, "unpack error");
246                 return -EINVAL;
247         }
248
249         return 0;
250 }
251
252 int bch2_alloc_v3_invalid(const struct bch_fs *c, struct bkey_s_c k,
253                           int rw, struct printbuf *err)
254 {
255         struct bkey_alloc_unpacked u;
256
257         if (bch2_alloc_unpack_v3(&u, k)) {
258                 prt_printf(err, "unpack error");
259                 return -EINVAL;
260         }
261
262         return 0;
263 }
264
265 int bch2_alloc_v4_invalid(const struct bch_fs *c, struct bkey_s_c k,
266                           int rw, struct printbuf *err)
267 {
268         struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);
269
270         if (alloc_v4_u64s(a.v) != bkey_val_u64s(k.k)) {
271                 prt_printf(err, "bad val size (%lu != %u)",
272                        bkey_val_u64s(k.k), alloc_v4_u64s(a.v));
273                 return -EINVAL;
274         }
275
276         if (!BCH_ALLOC_V4_BACKPOINTERS_START(a.v) &&
277             BCH_ALLOC_V4_NR_BACKPOINTERS(a.v)) {
278                 prt_printf(err, "invalid backpointers_start");
279                 return -EINVAL;
280         }
281
282         /*
283          * XXX this is wrong, we'll be checking updates that happened from
284          * before BCH_FS_CHECK_BACKPOINTERS_DONE
285          */
286         if (rw == WRITE && test_bit(BCH_FS_CHECK_BACKPOINTERS_DONE, &c->flags)) {
287                 unsigned i, bp_len = 0;
288
289                 for (i = 0; i < BCH_ALLOC_V4_NR_BACKPOINTERS(a.v); i++)
290                         bp_len += alloc_v4_backpointers_c(a.v)[i].bucket_len;
291
292                 if (bp_len > a.v->dirty_sectors) {
293                         prt_printf(err, "too many backpointers");
294                         return -EINVAL;
295                 }
296         }
297
298         if (rw == WRITE) {
299                 if (alloc_data_type(*a.v, a.v->data_type) != a.v->data_type) {
300                         prt_printf(err, "invalid data type (got %u should be %u)",
301                                a.v->data_type, alloc_data_type(*a.v, a.v->data_type));
302                         return -EINVAL;
303                 }
304
305                 switch (a.v->data_type) {
306                 case BCH_DATA_free:
307                 case BCH_DATA_need_gc_gens:
308                 case BCH_DATA_need_discard:
309                         if (a.v->dirty_sectors ||
310                             a.v->cached_sectors ||
311                             a.v->stripe) {
312                                 prt_printf(err, "empty data type free but have data");
313                                 return -EINVAL;
314                         }
315                         break;
316                 case BCH_DATA_sb:
317                 case BCH_DATA_journal:
318                 case BCH_DATA_btree:
319                 case BCH_DATA_user:
320                 case BCH_DATA_parity:
321                         if (!a.v->dirty_sectors) {
322                                 prt_printf(err, "data_type %s but dirty_sectors==0",
323                                        bch2_data_types[a.v->data_type]);
324                                 return -EINVAL;
325                         }
326                         break;
327                 case BCH_DATA_cached:
328                         if (!a.v->cached_sectors ||
329                             a.v->dirty_sectors ||
330                             a.v->stripe) {
331                                 prt_printf(err, "data type inconsistency");
332                                 return -EINVAL;
333                         }
334
335                         if (!a.v->io_time[READ] &&
336                             test_bit(BCH_FS_CHECK_ALLOC_TO_LRU_REFS_DONE, &c->flags)) {
337                                 prt_printf(err, "cached bucket with read_time == 0");
338                                 return -EINVAL;
339                         }
340                         break;
341                 case BCH_DATA_stripe:
342                         if (!a.v->stripe) {
343                                 prt_printf(err, "data_type %s but stripe==0",
344                                        bch2_data_types[a.v->data_type]);
345                                 return -EINVAL;
346                         }
347                         break;
348                 }
349         }
350
351         return 0;
352 }
353
354 static inline u64 swab40(u64 x)
355 {
356         return (((x & 0x00000000ffULL) << 32)|
357                 ((x & 0x000000ff00ULL) << 16)|
358                 ((x & 0x0000ff0000ULL) >>  0)|
359                 ((x & 0x00ff000000ULL) >> 16)|
360                 ((x & 0xff00000000ULL) >> 32));
361 }
362
363 void bch2_alloc_v4_swab(struct bkey_s k)
364 {
365         struct bch_alloc_v4 *a = bkey_s_to_alloc_v4(k).v;
366         struct bch_backpointer *bp, *bps;
367
368         a->journal_seq          = swab64(a->journal_seq);
369         a->flags                = swab32(a->flags);
370         a->dirty_sectors        = swab32(a->dirty_sectors);
371         a->cached_sectors       = swab32(a->cached_sectors);
372         a->io_time[0]           = swab64(a->io_time[0]);
373         a->io_time[1]           = swab64(a->io_time[1]);
374         a->stripe               = swab32(a->stripe);
375         a->nr_external_backpointers = swab32(a->nr_external_backpointers);
376
377         bps = alloc_v4_backpointers(a);
378         for (bp = bps; bp < bps + BCH_ALLOC_V4_NR_BACKPOINTERS(a); bp++) {
379                 bp->bucket_offset       = swab40(bp->bucket_offset);
380                 bp->bucket_len          = swab32(bp->bucket_len);
381                 bch2_bpos_swab(&bp->pos);
382         }
383 }
384
385 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
386 {
387         struct bch_alloc_v4 _a;
388         const struct bch_alloc_v4 *a = &_a;
389         const struct bch_backpointer *bps;
390         unsigned i;
391
392         if (k.k->type == KEY_TYPE_alloc_v4)
393                 a = bkey_s_c_to_alloc_v4(k).v;
394         else
395                 bch2_alloc_to_v4(k, &_a);
396
397         prt_newline(out);
398         printbuf_indent_add(out, 2);
399
400         prt_printf(out, "gen %u oldest_gen %u data_type %s",
401                a->gen, a->oldest_gen, bch2_data_types[a->data_type]);
402         prt_newline(out);
403         prt_printf(out, "journal_seq       %llu",       a->journal_seq);
404         prt_newline(out);
405         prt_printf(out, "need_discard      %llu",       BCH_ALLOC_V4_NEED_DISCARD(a));
406         prt_newline(out);
407         prt_printf(out, "need_inc_gen      %llu",       BCH_ALLOC_V4_NEED_INC_GEN(a));
408         prt_newline(out);
409         prt_printf(out, "dirty_sectors     %u", a->dirty_sectors);
410         prt_newline(out);
411         prt_printf(out, "cached_sectors    %u", a->cached_sectors);
412         prt_newline(out);
413         prt_printf(out, "stripe            %u", a->stripe);
414         prt_newline(out);
415         prt_printf(out, "stripe_redundancy %u", a->stripe_redundancy);
416         prt_newline(out);
417         prt_printf(out, "io_time[READ]     %llu",       a->io_time[READ]);
418         prt_newline(out);
419         prt_printf(out, "io_time[WRITE]    %llu",       a->io_time[WRITE]);
420         prt_newline(out);
421         prt_printf(out, "backpointers:     %llu",       BCH_ALLOC_V4_NR_BACKPOINTERS(a));
422         printbuf_indent_add(out, 2);
423
424         bps = alloc_v4_backpointers_c(a);
425         for (i = 0; i < BCH_ALLOC_V4_NR_BACKPOINTERS(a); i++) {
426                 prt_newline(out);
427                 bch2_backpointer_to_text(out, &bps[i]);
428         }
429
430         printbuf_indent_sub(out, 4);
431 }
432
433 void bch2_alloc_to_v4(struct bkey_s_c k, struct bch_alloc_v4 *out)
434 {
435         if (k.k->type == KEY_TYPE_alloc_v4) {
436                 int d;
437
438                 *out = *bkey_s_c_to_alloc_v4(k).v;
439
440                 d = (int) BCH_ALLOC_V4_U64s -
441                         (int) (BCH_ALLOC_V4_BACKPOINTERS_START(out) ?: BCH_ALLOC_V4_U64s_V0);
442                 if (unlikely(d > 0)) {
443                         memset((u64 *) out + BCH_ALLOC_V4_BACKPOINTERS_START(out),
444                                0,
445                                d * sizeof(u64));
446                         SET_BCH_ALLOC_V4_BACKPOINTERS_START(out, BCH_ALLOC_V4_U64s);
447                 }
448         } else {
449                 struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);
450
451                 *out = (struct bch_alloc_v4) {
452                         .journal_seq            = u.journal_seq,
453                         .flags                  = u.need_discard,
454                         .gen                    = u.gen,
455                         .oldest_gen             = u.oldest_gen,
456                         .data_type              = u.data_type,
457                         .stripe_redundancy      = u.stripe_redundancy,
458                         .dirty_sectors          = u.dirty_sectors,
459                         .cached_sectors         = u.cached_sectors,
460                         .io_time[READ]          = u.read_time,
461                         .io_time[WRITE]         = u.write_time,
462                         .stripe                 = u.stripe,
463                 };
464
465                 SET_BCH_ALLOC_V4_BACKPOINTERS_START(out, BCH_ALLOC_V4_U64s);
466         }
467 }
468
469 static noinline struct bkey_i_alloc_v4 *
470 __bch2_alloc_to_v4_mut(struct btree_trans *trans, struct bkey_s_c k)
471 {
472         struct bkey_i_alloc_v4 *ret;
473         unsigned bytes = k.k->type == KEY_TYPE_alloc_v4
474                 ? bkey_bytes(k.k)
475                 : sizeof(struct bkey_i_alloc_v4);
476
477         /*
478          * Reserve space for one more backpointer here:
479          * Not sketchy at doing it this way, nope...
480          */
481         ret = bch2_trans_kmalloc(trans, bytes + sizeof(struct bch_backpointer));
482         if (IS_ERR(ret))
483                 return ret;
484
485         if (k.k->type == KEY_TYPE_alloc_v4) {
486                 struct bch_backpointer *src, *dst;
487
488                 bkey_reassemble(&ret->k_i, k);
489
490                 src = alloc_v4_backpointers(&ret->v);
491                 SET_BCH_ALLOC_V4_BACKPOINTERS_START(&ret->v, BCH_ALLOC_V4_U64s);
492                 dst = alloc_v4_backpointers(&ret->v);
493
494                 memmove(dst, src, BCH_ALLOC_V4_NR_BACKPOINTERS(&ret->v) *
495                         sizeof(struct bch_backpointer));
496                 memset(src, 0, dst - src);
497                 set_alloc_v4_u64s(ret);
498         } else {
499                 bkey_alloc_v4_init(&ret->k_i);
500                 ret->k.p = k.k->p;
501                 bch2_alloc_to_v4(k, &ret->v);
502         }
503         return ret;
504 }
505
506 static inline struct bkey_i_alloc_v4 *bch2_alloc_to_v4_mut_inlined(struct btree_trans *trans, struct bkey_s_c k)
507 {
508         if (likely(k.k->type == KEY_TYPE_alloc_v4) &&
509             BCH_ALLOC_V4_BACKPOINTERS_START(bkey_s_c_to_alloc_v4(k).v) == BCH_ALLOC_V4_U64s) {
510                 /*
511                  * Reserve space for one more backpointer here:
512                  * Not sketchy at doing it this way, nope...
513                  */
514                 struct bkey_i_alloc_v4 *ret =
515                         bch2_trans_kmalloc(trans, bkey_bytes(k.k) + sizeof(struct bch_backpointer));
516                 if (!IS_ERR(ret))
517                         bkey_reassemble(&ret->k_i, k);
518                 return ret;
519         }
520
521         return __bch2_alloc_to_v4_mut(trans, k);
522 }
523
524 struct bkey_i_alloc_v4 *bch2_alloc_to_v4_mut(struct btree_trans *trans, struct bkey_s_c k)
525 {
526         return bch2_alloc_to_v4_mut_inlined(trans, k);
527 }
528
529 struct bkey_i_alloc_v4 *
530 bch2_trans_start_alloc_update(struct btree_trans *trans, struct btree_iter *iter,
531                               struct bpos pos)
532 {
533         struct bkey_s_c k;
534         struct bkey_i_alloc_v4 *a;
535         int ret;
536
537         bch2_trans_iter_init(trans, iter, BTREE_ID_alloc, pos,
538                              BTREE_ITER_WITH_UPDATES|
539                              BTREE_ITER_CACHED|
540                              BTREE_ITER_INTENT);
541         k = bch2_btree_iter_peek_slot(iter);
542         ret = bkey_err(k);
543         if (ret) {
544                 bch2_trans_iter_exit(trans, iter);
545                 return ERR_PTR(ret);
546         }
547
548         a = bch2_alloc_to_v4_mut_inlined(trans, k);
549         if (IS_ERR(a))
550                 bch2_trans_iter_exit(trans, iter);
551         return a;
552 }
553
554 int bch2_alloc_read(struct bch_fs *c)
555 {
556         struct btree_trans trans;
557         struct btree_iter iter;
558         struct bkey_s_c k;
559         struct bch_alloc_v4 a;
560         struct bch_dev *ca;
561         int ret;
562
563         bch2_trans_init(&trans, c, 0, 0);
564
565         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
566                            BTREE_ITER_PREFETCH, k, ret) {
567                 /*
568                  * Not a fsck error because this is checked/repaired by
569                  * bch2_check_alloc_key() which runs later:
570                  */
571                 if (!bch2_dev_bucket_exists(c, k.k->p))
572                         continue;
573
574                 ca = bch_dev_bkey_exists(c, k.k->p.inode);
575                 bch2_alloc_to_v4(k, &a);
576
577                 *bucket_gen(ca, k.k->p.offset) = a.gen;
578         }
579         bch2_trans_iter_exit(&trans, &iter);
580
581         bch2_trans_exit(&trans);
582
583         if (ret)
584                 bch_err(c, "error reading alloc info: %s", bch2_err_str(ret));
585
586         return ret;
587 }
588
589 /* Free space/discard btree: */
590
591 static int bch2_bucket_do_index(struct btree_trans *trans,
592                                 struct bkey_s_c alloc_k,
593                                 const struct bch_alloc_v4 *a,
594                                 bool set)
595 {
596         struct bch_fs *c = trans->c;
597         struct bch_dev *ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
598         struct btree_iter iter;
599         struct bkey_s_c old;
600         struct bkey_i *k;
601         enum btree_id btree;
602         enum bch_bkey_type old_type = !set ? KEY_TYPE_set : KEY_TYPE_deleted;
603         enum bch_bkey_type new_type =  set ? KEY_TYPE_set : KEY_TYPE_deleted;
604         struct printbuf buf = PRINTBUF;
605         int ret;
606
607         if (a->data_type != BCH_DATA_free &&
608             a->data_type != BCH_DATA_need_discard)
609                 return 0;
610
611         k = bch2_trans_kmalloc(trans, sizeof(*k));
612         if (IS_ERR(k))
613                 return PTR_ERR(k);
614
615         bkey_init(&k->k);
616         k->k.type = new_type;
617
618         switch (a->data_type) {
619         case BCH_DATA_free:
620                 btree = BTREE_ID_freespace;
621                 k->k.p = alloc_freespace_pos(alloc_k.k->p, *a);
622                 bch2_key_resize(&k->k, 1);
623                 break;
624         case BCH_DATA_need_discard:
625                 btree = BTREE_ID_need_discard;
626                 k->k.p = alloc_k.k->p;
627                 break;
628         default:
629                 return 0;
630         }
631
632         bch2_trans_iter_init(trans, &iter, btree,
633                              bkey_start_pos(&k->k),
634                              BTREE_ITER_INTENT);
635         old = bch2_btree_iter_peek_slot(&iter);
636         ret = bkey_err(old);
637         if (ret)
638                 goto err;
639
640         if (ca->mi.freespace_initialized &&
641             bch2_trans_inconsistent_on(old.k->type != old_type, trans,
642                         "incorrect key when %s %s btree (got %s should be %s)\n"
643                         "  for %s",
644                         set ? "setting" : "clearing",
645                         bch2_btree_ids[btree],
646                         bch2_bkey_types[old.k->type],
647                         bch2_bkey_types[old_type],
648                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
649                 ret = -EIO;
650                 goto err;
651         }
652
653         ret = bch2_trans_update(trans, &iter, k, 0);
654 err:
655         bch2_trans_iter_exit(trans, &iter);
656         printbuf_exit(&buf);
657         return ret;
658 }
659
660 int bch2_trans_mark_alloc(struct btree_trans *trans,
661                           enum btree_id btree_id, unsigned level,
662                           struct bkey_s_c old, struct bkey_i *new,
663                           unsigned flags)
664 {
665         struct bch_fs *c = trans->c;
666         struct bch_alloc_v4 old_a, *new_a;
667         u64 old_lru, new_lru;
668         int ret = 0;
669
670         /*
671          * Deletion only happens in the device removal path, with
672          * BTREE_TRIGGER_NORUN:
673          */
674         BUG_ON(new->k.type != KEY_TYPE_alloc_v4);
675
676         bch2_alloc_to_v4(old, &old_a);
677         new_a = &bkey_i_to_alloc_v4(new)->v;
678
679         new_a->data_type = alloc_data_type(*new_a, new_a->data_type);
680
681         if (new_a->dirty_sectors > old_a.dirty_sectors ||
682             new_a->cached_sectors > old_a.cached_sectors) {
683                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
684                 new_a->io_time[WRITE]= max_t(u64, 1, atomic64_read(&c->io_clock[WRITE].now));
685                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, true);
686                 SET_BCH_ALLOC_V4_NEED_DISCARD(new_a, true);
687         }
688
689         if (data_type_is_empty(new_a->data_type) &&
690             BCH_ALLOC_V4_NEED_INC_GEN(new_a) &&
691             !bch2_bucket_is_open_safe(c, new->k.p.inode, new->k.p.offset)) {
692                 new_a->gen++;
693                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, false);
694         }
695
696         if (old_a.data_type != new_a->data_type ||
697             (new_a->data_type == BCH_DATA_free &&
698              alloc_freespace_genbits(old_a) != alloc_freespace_genbits(*new_a))) {
699                 ret =   bch2_bucket_do_index(trans, old, &old_a, false) ?:
700                         bch2_bucket_do_index(trans, bkey_i_to_s_c(new), new_a, true);
701                 if (ret)
702                         return ret;
703         }
704
705         if (new_a->data_type == BCH_DATA_cached &&
706             !new_a->io_time[READ])
707                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
708
709         old_lru = alloc_lru_idx(old_a);
710         new_lru = alloc_lru_idx(*new_a);
711
712         if (old_lru != new_lru) {
713                 ret = bch2_lru_change(trans, new->k.p.inode, new->k.p.offset,
714                                       old_lru, &new_lru, old);
715                 if (ret)
716                         return ret;
717
718                 if (new_a->data_type == BCH_DATA_cached)
719                         new_a->io_time[READ] = new_lru;
720         }
721
722         return 0;
723 }
724
725 static int bch2_check_alloc_key(struct btree_trans *trans,
726                                 struct btree_iter *alloc_iter,
727                                 struct btree_iter *discard_iter,
728                                 struct btree_iter *freespace_iter)
729 {
730         struct bch_fs *c = trans->c;
731         struct bch_dev *ca;
732         struct bch_alloc_v4 a;
733         unsigned discard_key_type, freespace_key_type;
734         struct bkey_s_c alloc_k, k;
735         struct printbuf buf = PRINTBUF;
736         int ret;
737
738         alloc_k = bch2_dev_bucket_exists(c, alloc_iter->pos)
739                 ? bch2_btree_iter_peek_slot(alloc_iter)
740                 : bch2_btree_iter_peek(alloc_iter);
741         if (!alloc_k.k)
742                 return 1;
743
744         ret = bkey_err(alloc_k);
745         if (ret)
746                 return ret;
747
748         if (fsck_err_on(!bch2_dev_bucket_exists(c, alloc_k.k->p), c,
749                         "alloc key for invalid device:bucket %llu:%llu",
750                         alloc_k.k->p.inode, alloc_k.k->p.offset))
751                 return bch2_btree_delete_at(trans, alloc_iter, 0);
752
753         ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
754         if (!ca->mi.freespace_initialized)
755                 return 0;
756
757         bch2_alloc_to_v4(alloc_k, &a);
758
759         discard_key_type = a.data_type == BCH_DATA_need_discard
760                 ? KEY_TYPE_set : 0;
761         freespace_key_type = a.data_type == BCH_DATA_free
762                 ? KEY_TYPE_set : 0;
763
764         bch2_btree_iter_set_pos(discard_iter, alloc_k.k->p);
765         bch2_btree_iter_set_pos(freespace_iter, alloc_freespace_pos(alloc_k.k->p, a));
766
767         k = bch2_btree_iter_peek_slot(discard_iter);
768         ret = bkey_err(k);
769         if (ret)
770                 goto err;
771
772         if (k.k->type != discard_key_type &&
773             (c->opts.reconstruct_alloc ||
774              fsck_err(c, "incorrect key in need_discard btree (got %s should be %s)\n"
775                       "  %s",
776                       bch2_bkey_types[k.k->type],
777                       bch2_bkey_types[discard_key_type],
778                       (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)))) {
779                 struct bkey_i *update =
780                         bch2_trans_kmalloc(trans, sizeof(*update));
781
782                 ret = PTR_ERR_OR_ZERO(update);
783                 if (ret)
784                         goto err;
785
786                 bkey_init(&update->k);
787                 update->k.type  = discard_key_type;
788                 update->k.p     = discard_iter->pos;
789
790                 ret = bch2_trans_update(trans, discard_iter, update, 0);
791                 if (ret)
792                         goto err;
793         }
794
795         k = bch2_btree_iter_peek_slot(freespace_iter);
796         ret = bkey_err(k);
797         if (ret)
798                 goto err;
799
800         if (k.k->type != freespace_key_type &&
801             (c->opts.reconstruct_alloc ||
802              fsck_err(c, "incorrect key in freespace btree (got %s should be %s)\n"
803                       "  %s",
804                       bch2_bkey_types[k.k->type],
805                       bch2_bkey_types[freespace_key_type],
806                       (printbuf_reset(&buf),
807                        bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)))) {
808                 struct bkey_i *update =
809                         bch2_trans_kmalloc(trans, sizeof(*update));
810
811                 ret = PTR_ERR_OR_ZERO(update);
812                 if (ret)
813                         goto err;
814
815                 bkey_init(&update->k);
816                 update->k.type  = freespace_key_type;
817                 update->k.p     = freespace_iter->pos;
818                 bch2_key_resize(&update->k, 1);
819
820                 ret = bch2_trans_update(trans, freespace_iter, update, 0);
821                 if (ret)
822                         goto err;
823         }
824 err:
825 fsck_err:
826         printbuf_exit(&buf);
827         return ret;
828 }
829
830 static int bch2_check_discard_freespace_key(struct btree_trans *trans,
831                                             struct btree_iter *iter)
832 {
833         struct bch_fs *c = trans->c;
834         struct btree_iter alloc_iter;
835         struct bkey_s_c alloc_k;
836         struct bch_alloc_v4 a;
837         u64 genbits;
838         struct bpos pos;
839         enum bch_data_type state = iter->btree_id == BTREE_ID_need_discard
840                 ? BCH_DATA_need_discard
841                 : BCH_DATA_free;
842         struct printbuf buf = PRINTBUF;
843         int ret;
844
845         pos = iter->pos;
846         pos.offset &= ~(~0ULL << 56);
847         genbits = iter->pos.offset & (~0ULL << 56);
848
849         bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc, pos, 0);
850
851         if (fsck_err_on(!bch2_dev_bucket_exists(c, pos), c,
852                         "entry in %s btree for nonexistant dev:bucket %llu:%llu",
853                         bch2_btree_ids[iter->btree_id], pos.inode, pos.offset))
854                 goto delete;
855
856         alloc_k = bch2_btree_iter_peek_slot(&alloc_iter);
857         ret = bkey_err(alloc_k);
858         if (ret)
859                 goto err;
860
861         bch2_alloc_to_v4(alloc_k, &a);
862
863         if (fsck_err_on(a.data_type != state ||
864                         (state == BCH_DATA_free &&
865                          genbits != alloc_freespace_genbits(a)), c,
866                         "%s\n  incorrectly set in %s index (free %u, genbits %llu should be %llu)",
867                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
868                         bch2_btree_ids[iter->btree_id],
869                         a.data_type == state,
870                         genbits >> 56, alloc_freespace_genbits(a) >> 56))
871                 goto delete;
872 out:
873 err:
874 fsck_err:
875         bch2_trans_iter_exit(trans, &alloc_iter);
876         printbuf_exit(&buf);
877         return ret;
878 delete:
879         ret = bch2_btree_delete_extent_at(trans, iter,
880                         iter->btree_id == BTREE_ID_freespace ? 1 : 0, 0);
881         goto out;
882 }
883
884 int bch2_check_alloc_info(struct bch_fs *c)
885 {
886         struct btree_trans trans;
887         struct btree_iter iter, discard_iter, freespace_iter;
888         struct bkey_s_c k;
889         int ret = 0;
890
891         bch2_trans_init(&trans, c, 0, 0);
892
893         bch2_trans_iter_init(&trans, &iter, BTREE_ID_alloc, POS_MIN,
894                              BTREE_ITER_PREFETCH);
895         bch2_trans_iter_init(&trans, &discard_iter, BTREE_ID_need_discard, POS_MIN,
896                              BTREE_ITER_PREFETCH);
897         bch2_trans_iter_init(&trans, &freespace_iter, BTREE_ID_freespace, POS_MIN,
898                              BTREE_ITER_PREFETCH);
899         while (1) {
900                 ret = commit_do(&trans, NULL, NULL,
901                                       BTREE_INSERT_NOFAIL|
902                                       BTREE_INSERT_LAZY_RW,
903                         bch2_check_alloc_key(&trans, &iter,
904                                              &discard_iter,
905                                              &freespace_iter));
906                 if (ret)
907                         break;
908
909                 bch2_btree_iter_advance(&iter);
910         }
911         bch2_trans_iter_exit(&trans, &freespace_iter);
912         bch2_trans_iter_exit(&trans, &discard_iter);
913         bch2_trans_iter_exit(&trans, &iter);
914
915         if (ret < 0)
916                 goto err;
917
918         ret = for_each_btree_key_commit(&trans, iter,
919                         BTREE_ID_need_discard, POS_MIN,
920                         BTREE_ITER_PREFETCH, k,
921                         NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
922                 bch2_check_discard_freespace_key(&trans, &iter)) ?:
923               for_each_btree_key_commit(&trans, iter,
924                         BTREE_ID_freespace, POS_MIN,
925                         BTREE_ITER_PREFETCH, k,
926                         NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
927                 bch2_check_discard_freespace_key(&trans, &iter));
928 err:
929         bch2_trans_exit(&trans);
930         return ret < 0 ? ret : 0;
931 }
932
933 static int bch2_check_alloc_to_lru_ref(struct btree_trans *trans,
934                                        struct btree_iter *alloc_iter)
935 {
936         struct bch_fs *c = trans->c;
937         struct btree_iter lru_iter;
938         struct bch_alloc_v4 a;
939         struct bkey_s_c alloc_k, k;
940         struct printbuf buf = PRINTBUF;
941         struct printbuf buf2 = PRINTBUF;
942         int ret;
943
944         alloc_k = bch2_btree_iter_peek(alloc_iter);
945         if (!alloc_k.k)
946                 return 0;
947
948         ret = bkey_err(alloc_k);
949         if (ret)
950                 return ret;
951
952         bch2_alloc_to_v4(alloc_k, &a);
953
954         if (a.data_type != BCH_DATA_cached)
955                 return 0;
956
957         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
958                              POS(alloc_k.k->p.inode, a.io_time[READ]), 0);
959
960         k = bch2_btree_iter_peek_slot(&lru_iter);
961         ret = bkey_err(k);
962         if (ret)
963                 goto err;
964
965         if (fsck_err_on(!a.io_time[READ], c,
966                         "cached bucket with read_time 0\n"
967                         "  %s",
968                 (printbuf_reset(&buf),
969                  bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)) ||
970             fsck_err_on(k.k->type != KEY_TYPE_lru ||
971                         le64_to_cpu(bkey_s_c_to_lru(k).v->idx) != alloc_k.k->p.offset, c,
972                         "incorrect/missing lru entry\n"
973                         "  %s\n"
974                         "  %s",
975                         (printbuf_reset(&buf),
976                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
977                         (bch2_bkey_val_to_text(&buf2, c, k), buf2.buf))) {
978                 u64 read_time = a.io_time[READ];
979
980                 if (!a.io_time[READ])
981                         a.io_time[READ] = atomic64_read(&c->io_clock[READ].now);
982
983                 ret = bch2_lru_set(trans,
984                                    alloc_k.k->p.inode,
985                                    alloc_k.k->p.offset,
986                                    &a.io_time[READ]);
987                 if (ret)
988                         goto err;
989
990                 if (a.io_time[READ] != read_time) {
991                         struct bkey_i_alloc_v4 *a_mut =
992                                 bch2_alloc_to_v4_mut(trans, alloc_k);
993                         ret = PTR_ERR_OR_ZERO(a_mut);
994                         if (ret)
995                                 goto err;
996
997                         a_mut->v.io_time[READ] = a.io_time[READ];
998                         ret = bch2_trans_update(trans, alloc_iter,
999                                                 &a_mut->k_i, BTREE_TRIGGER_NORUN);
1000                         if (ret)
1001                                 goto err;
1002                 }
1003         }
1004 err:
1005 fsck_err:
1006         bch2_trans_iter_exit(trans, &lru_iter);
1007         printbuf_exit(&buf2);
1008         printbuf_exit(&buf);
1009         return ret;
1010 }
1011
1012 int bch2_check_alloc_to_lru_refs(struct bch_fs *c)
1013 {
1014         struct btree_trans trans;
1015         struct btree_iter iter;
1016         struct bkey_s_c k;
1017         int ret = 0;
1018
1019         bch2_trans_init(&trans, c, 0, 0);
1020
1021         for_each_btree_key_commit(&trans, iter, BTREE_ID_alloc,
1022                         POS_MIN, BTREE_ITER_PREFETCH, k,
1023                         NULL, NULL, BTREE_INSERT_NOFAIL|BTREE_INSERT_LAZY_RW,
1024                 bch2_check_alloc_to_lru_ref(&trans, &iter));
1025
1026         bch2_trans_exit(&trans);
1027         return ret < 0 ? ret : 0;
1028 }
1029
1030 static int bch2_discard_one_bucket(struct btree_trans *trans,
1031                                    struct btree_iter *need_discard_iter,
1032                                    struct bpos *discard_pos_done,
1033                                    u64 *seen,
1034                                    u64 *open,
1035                                    u64 *need_journal_commit,
1036                                    u64 *discarded)
1037 {
1038         struct bch_fs *c = trans->c;
1039         struct bpos pos = need_discard_iter->pos;
1040         struct btree_iter iter = { NULL };
1041         struct bkey_s_c k;
1042         struct bch_dev *ca;
1043         struct bkey_i_alloc_v4 *a;
1044         struct printbuf buf = PRINTBUF;
1045         bool did_discard = false;
1046         int ret = 0;
1047
1048         ca = bch_dev_bkey_exists(c, pos.inode);
1049         if (!percpu_ref_tryget(&ca->io_ref)) {
1050                 bch2_btree_iter_set_pos(need_discard_iter, POS(pos.inode + 1, 0));
1051                 return 0;
1052         }
1053
1054         if (bch2_bucket_is_open_safe(c, pos.inode, pos.offset)) {
1055                 (*open)++;
1056                 goto out;
1057         }
1058
1059         if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
1060                         c->journal.flushed_seq_ondisk,
1061                         pos.inode, pos.offset)) {
1062                 (*need_journal_commit)++;
1063                 goto out;
1064         }
1065
1066         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
1067                              need_discard_iter->pos,
1068                              BTREE_ITER_CACHED);
1069         k = bch2_btree_iter_peek_slot(&iter);
1070         ret = bkey_err(k);
1071         if (ret)
1072                 goto out;
1073
1074         a = bch2_alloc_to_v4_mut(trans, k);
1075         ret = PTR_ERR_OR_ZERO(a);
1076         if (ret)
1077                 goto out;
1078
1079         if (BCH_ALLOC_V4_NEED_INC_GEN(&a->v)) {
1080                 a->v.gen++;
1081                 SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1082                 goto write;
1083         }
1084
1085         if (bch2_trans_inconsistent_on(a->v.journal_seq > c->journal.flushed_seq_ondisk, trans,
1086                         "clearing need_discard but journal_seq %llu > flushed_seq %llu\n"
1087                         "%s",
1088                         a->v.journal_seq,
1089                         c->journal.flushed_seq_ondisk,
1090                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1091                 ret = -EIO;
1092                 goto out;
1093         }
1094
1095         if (bch2_trans_inconsistent_on(a->v.data_type != BCH_DATA_need_discard, trans,
1096                         "bucket incorrectly set in need_discard btree\n"
1097                         "%s",
1098                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1099                 ret = -EIO;
1100                 goto out;
1101         }
1102
1103         if (bkey_cmp(*discard_pos_done, iter.pos) &&
1104             ca->mi.discard && !c->opts.nochanges) {
1105                 /*
1106                  * This works without any other locks because this is the only
1107                  * thread that removes items from the need_discard tree
1108                  */
1109                 bch2_trans_unlock(trans);
1110                 blkdev_issue_discard(ca->disk_sb.bdev,
1111                                      k.k->p.offset * ca->mi.bucket_size,
1112                                      ca->mi.bucket_size,
1113                                      GFP_KERNEL);
1114
1115                 ret = bch2_trans_relock(trans);
1116                 if (ret)
1117                         goto out;
1118         }
1119
1120         *discard_pos_done = iter.pos;
1121         did_discard = true;
1122
1123         SET_BCH_ALLOC_V4_NEED_DISCARD(&a->v, false);
1124         a->v.data_type = alloc_data_type(a->v, a->v.data_type);
1125 write:
1126         ret =   bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1127                 bch2_trans_commit(trans, NULL, NULL,
1128                                   BTREE_INSERT_USE_RESERVE|BTREE_INSERT_NOFAIL);
1129         if (ret)
1130                 goto out;
1131
1132         if (did_discard) {
1133                 this_cpu_inc(c->counters[BCH_COUNTER_bucket_discard]);
1134                 (*discarded)++;
1135         }
1136 out:
1137         bch2_trans_iter_exit(trans, &iter);
1138         percpu_ref_put(&ca->io_ref);
1139         printbuf_exit(&buf);
1140         return ret;
1141 }
1142
1143 static void bch2_do_discards_work(struct work_struct *work)
1144 {
1145         struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
1146         struct btree_trans trans;
1147         struct btree_iter iter;
1148         struct bkey_s_c k;
1149         u64 seen = 0, open = 0, need_journal_commit = 0, discarded = 0;
1150         struct bpos discard_pos_done = POS_MAX;
1151         int ret;
1152
1153         bch2_trans_init(&trans, c, 0, 0);
1154
1155         /*
1156          * We're doing the commit in bch2_discard_one_bucket instead of using
1157          * for_each_btree_key_commit() so that we can increment counters after
1158          * successful commit:
1159          */
1160         ret = for_each_btree_key2(&trans, iter,
1161                         BTREE_ID_need_discard, POS_MIN, 0, k,
1162                 bch2_discard_one_bucket(&trans, &iter, &discard_pos_done,
1163                                         &seen,
1164                                         &open,
1165                                         &need_journal_commit,
1166                                         &discarded));
1167
1168         bch2_trans_exit(&trans);
1169
1170         if (need_journal_commit * 2 > seen)
1171                 bch2_journal_flush_async(&c->journal, NULL);
1172
1173         percpu_ref_put(&c->writes);
1174
1175         trace_discard_buckets(c, seen, open, need_journal_commit, discarded,
1176                               bch2_err_str(ret));
1177 }
1178
1179 void bch2_do_discards(struct bch_fs *c)
1180 {
1181         if (percpu_ref_tryget_live(&c->writes) &&
1182             !queue_work(system_long_wq, &c->discard_work))
1183                 percpu_ref_put(&c->writes);
1184 }
1185
1186 static int invalidate_one_bucket(struct btree_trans *trans,
1187                                  struct btree_iter *lru_iter, struct bkey_s_c k,
1188                                  unsigned dev_idx, s64 *nr_to_invalidate)
1189 {
1190         struct bch_fs *c = trans->c;
1191         struct btree_iter alloc_iter = { NULL };
1192         struct bkey_i_alloc_v4 *a;
1193         struct bpos bucket;
1194         struct printbuf buf = PRINTBUF;
1195         unsigned cached_sectors;
1196         int ret = 0;
1197
1198         if (*nr_to_invalidate <= 0 || k.k->p.inode != dev_idx)
1199                 return 1;
1200
1201         if (k.k->type != KEY_TYPE_lru) {
1202                 prt_printf(&buf, "non lru key in lru btree:\n  ");
1203                 bch2_bkey_val_to_text(&buf, c, k);
1204
1205                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1206                         bch_err(c, "%s", buf.buf);
1207                 } else {
1208                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1209                         ret = -EINVAL;
1210                 }
1211
1212                 goto out;
1213         }
1214
1215         bucket = POS(dev_idx, le64_to_cpu(bkey_s_c_to_lru(k).v->idx));
1216
1217         a = bch2_trans_start_alloc_update(trans, &alloc_iter, bucket);
1218         ret = PTR_ERR_OR_ZERO(a);
1219         if (ret)
1220                 goto out;
1221
1222         if (k.k->p.offset != alloc_lru_idx(a->v)) {
1223                 prt_printf(&buf, "alloc key does not point back to lru entry when invalidating bucket:\n  ");
1224                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&a->k_i));
1225                 prt_printf(&buf, "\n  ");
1226                 bch2_bkey_val_to_text(&buf, c, k);
1227
1228                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1229                         bch_err(c, "%s", buf.buf);
1230                 } else {
1231                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1232                         ret = -EINVAL;
1233                 }
1234
1235                 goto out;
1236         }
1237
1238         if (!a->v.cached_sectors)
1239                 bch_err(c, "invalidating empty bucket, confused");
1240
1241         cached_sectors = a->v.cached_sectors;
1242
1243         SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1244         a->v.gen++;
1245         a->v.data_type          = 0;
1246         a->v.dirty_sectors      = 0;
1247         a->v.cached_sectors     = 0;
1248         a->v.io_time[READ]      = atomic64_read(&c->io_clock[READ].now);
1249         a->v.io_time[WRITE]     = atomic64_read(&c->io_clock[WRITE].now);
1250
1251         ret =   bch2_trans_update(trans, &alloc_iter, &a->k_i,
1252                                 BTREE_TRIGGER_BUCKET_INVALIDATE) ?:
1253                 bch2_trans_commit(trans, NULL, NULL,
1254                                   BTREE_INSERT_USE_RESERVE|BTREE_INSERT_NOFAIL);
1255         if (ret)
1256                 goto out;
1257
1258         trace_and_count(c, bucket_invalidate, c, bucket.inode, bucket.offset, cached_sectors);
1259         --*nr_to_invalidate;
1260 out:
1261         bch2_trans_iter_exit(trans, &alloc_iter);
1262         printbuf_exit(&buf);
1263         return ret;
1264 }
1265
1266 static void bch2_do_invalidates_work(struct work_struct *work)
1267 {
1268         struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
1269         struct bch_dev *ca;
1270         struct btree_trans trans;
1271         struct btree_iter iter;
1272         struct bkey_s_c k;
1273         unsigned i;
1274         int ret = 0;
1275
1276         bch2_trans_init(&trans, c, 0, 0);
1277
1278         for_each_member_device(ca, c, i) {
1279                 s64 nr_to_invalidate =
1280                         should_invalidate_buckets(ca, bch2_dev_usage_read(ca));
1281
1282                 ret = for_each_btree_key2(&trans, iter, BTREE_ID_lru,
1283                                 POS(ca->dev_idx, 0), BTREE_ITER_INTENT, k,
1284                         invalidate_one_bucket(&trans, &iter, k, ca->dev_idx, &nr_to_invalidate));
1285
1286                 if (ret < 0) {
1287                         percpu_ref_put(&ca->ref);
1288                         break;
1289                 }
1290         }
1291
1292         bch2_trans_exit(&trans);
1293         percpu_ref_put(&c->writes);
1294 }
1295
1296 void bch2_do_invalidates(struct bch_fs *c)
1297 {
1298         if (percpu_ref_tryget_live(&c->writes) &&
1299             !queue_work(system_long_wq, &c->invalidate_work))
1300                 percpu_ref_put(&c->writes);
1301 }
1302
1303 static int bucket_freespace_init(struct btree_trans *trans, struct btree_iter *iter,
1304                                  struct bkey_s_c k, struct bch_dev *ca)
1305 {
1306         struct bch_alloc_v4 a;
1307
1308         if (iter->pos.offset >= ca->mi.nbuckets)
1309                 return 1;
1310
1311         bch2_alloc_to_v4(k, &a);
1312         return bch2_bucket_do_index(trans, k, &a, true);
1313 }
1314
1315 static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
1316 {
1317         struct btree_trans trans;
1318         struct btree_iter iter;
1319         struct bkey_s_c k;
1320         struct bch_member *m;
1321         int ret;
1322
1323         bch2_trans_init(&trans, c, 0, 0);
1324
1325         ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_alloc,
1326                         POS(ca->dev_idx, ca->mi.first_bucket),
1327                         BTREE_ITER_SLOTS|BTREE_ITER_PREFETCH, k,
1328                         NULL, NULL, BTREE_INSERT_LAZY_RW,
1329                 bucket_freespace_init(&trans, &iter, k, ca));
1330
1331         bch2_trans_exit(&trans);
1332
1333         if (ret < 0) {
1334                 bch_err(ca, "error initializing free space: %s", bch2_err_str(ret));
1335                 return ret;
1336         }
1337
1338         mutex_lock(&c->sb_lock);
1339         m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
1340         SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
1341         mutex_unlock(&c->sb_lock);
1342
1343         return 0;
1344 }
1345
1346 int bch2_fs_freespace_init(struct bch_fs *c)
1347 {
1348         struct bch_dev *ca;
1349         unsigned i;
1350         int ret = 0;
1351         bool doing_init = false;
1352
1353         /*
1354          * We can crash during the device add path, so we need to check this on
1355          * every mount:
1356          */
1357
1358         for_each_member_device(ca, c, i) {
1359                 if (ca->mi.freespace_initialized)
1360                         continue;
1361
1362                 if (!doing_init) {
1363                         bch_info(c, "initializing freespace");
1364                         doing_init = true;
1365                 }
1366
1367                 ret = bch2_dev_freespace_init(c, ca);
1368                 if (ret) {
1369                         percpu_ref_put(&ca->ref);
1370                         return ret;
1371                 }
1372         }
1373
1374         if (doing_init) {
1375                 mutex_lock(&c->sb_lock);
1376                 bch2_write_super(c);
1377                 mutex_unlock(&c->sb_lock);
1378
1379                 bch_verbose(c, "done initializing freespace");
1380         }
1381
1382         return ret;
1383 }
1384
1385 /* Bucket IO clocks: */
1386
1387 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
1388                               size_t bucket_nr, int rw)
1389 {
1390         struct bch_fs *c = trans->c;
1391         struct btree_iter iter;
1392         struct bkey_i_alloc_v4 *a;
1393         u64 now;
1394         int ret = 0;
1395
1396         a = bch2_trans_start_alloc_update(trans, &iter,  POS(dev, bucket_nr));
1397         ret = PTR_ERR_OR_ZERO(a);
1398         if (ret)
1399                 return ret;
1400
1401         now = atomic64_read(&c->io_clock[rw].now);
1402         if (a->v.io_time[rw] == now)
1403                 goto out;
1404
1405         a->v.io_time[rw] = now;
1406
1407         ret   = bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1408                 bch2_trans_commit(trans, NULL, NULL, 0);
1409 out:
1410         bch2_trans_iter_exit(trans, &iter);
1411         return ret;
1412 }
1413
1414 /* Startup/shutdown (ro/rw): */
1415
1416 void bch2_recalc_capacity(struct bch_fs *c)
1417 {
1418         struct bch_dev *ca;
1419         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1420         unsigned bucket_size_max = 0;
1421         unsigned long ra_pages = 0;
1422         unsigned i;
1423
1424         lockdep_assert_held(&c->state_lock);
1425
1426         for_each_online_member(ca, c, i) {
1427                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
1428
1429                 ra_pages += bdi->ra_pages;
1430         }
1431
1432         bch2_set_ra_pages(c, ra_pages);
1433
1434         for_each_rw_member(ca, c, i) {
1435                 u64 dev_reserve = 0;
1436
1437                 /*
1438                  * We need to reserve buckets (from the number
1439                  * of currently available buckets) against
1440                  * foreground writes so that mainly copygc can
1441                  * make forward progress.
1442                  *
1443                  * We need enough to refill the various reserves
1444                  * from scratch - copygc will use its entire
1445                  * reserve all at once, then run against when
1446                  * its reserve is refilled (from the formerly
1447                  * available buckets).
1448                  *
1449                  * This reserve is just used when considering if
1450                  * allocations for foreground writes must wait -
1451                  * not -ENOSPC calculations.
1452                  */
1453
1454                 dev_reserve += ca->nr_btree_reserve * 2;
1455                 dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1456
1457                 dev_reserve += 1;       /* btree write point */
1458                 dev_reserve += 1;       /* copygc write point */
1459                 dev_reserve += 1;       /* rebalance write point */
1460
1461                 dev_reserve *= ca->mi.bucket_size;
1462
1463                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1464                                              ca->mi.first_bucket);
1465
1466                 reserved_sectors += dev_reserve * 2;
1467
1468                 bucket_size_max = max_t(unsigned, bucket_size_max,
1469                                         ca->mi.bucket_size);
1470         }
1471
1472         gc_reserve = c->opts.gc_reserve_bytes
1473                 ? c->opts.gc_reserve_bytes >> 9
1474                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1475
1476         reserved_sectors = max(gc_reserve, reserved_sectors);
1477
1478         reserved_sectors = min(reserved_sectors, capacity);
1479
1480         c->capacity = capacity - reserved_sectors;
1481
1482         c->bucket_size_max = bucket_size_max;
1483
1484         /* Wake up case someone was waiting for buckets */
1485         closure_wake_up(&c->freelist_wait);
1486 }
1487
1488 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1489 {
1490         struct open_bucket *ob;
1491         bool ret = false;
1492
1493         for (ob = c->open_buckets;
1494              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1495              ob++) {
1496                 spin_lock(&ob->lock);
1497                 if (ob->valid && !ob->on_partial_list &&
1498                     ob->dev == ca->dev_idx)
1499                         ret = true;
1500                 spin_unlock(&ob->lock);
1501         }
1502
1503         return ret;
1504 }
1505
1506 /* device goes ro: */
1507 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1508 {
1509         unsigned i;
1510
1511         /* First, remove device from allocation groups: */
1512
1513         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1514                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1515
1516         /*
1517          * Capacity is calculated based off of devices in allocation groups:
1518          */
1519         bch2_recalc_capacity(c);
1520
1521         /* Next, close write points that point to this device... */
1522         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1523                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1524
1525         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1526         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1527         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1528
1529         mutex_lock(&c->btree_reserve_cache_lock);
1530         while (c->btree_reserve_cache_nr) {
1531                 struct btree_alloc *a =
1532                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1533
1534                 bch2_open_buckets_put(c, &a->ob);
1535         }
1536         mutex_unlock(&c->btree_reserve_cache_lock);
1537
1538         while (1) {
1539                 struct open_bucket *ob;
1540
1541                 spin_lock(&c->freelist_lock);
1542                 if (!ca->open_buckets_partial_nr) {
1543                         spin_unlock(&c->freelist_lock);
1544                         break;
1545                 }
1546                 ob = c->open_buckets +
1547                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1548                 ob->on_partial_list = false;
1549                 spin_unlock(&c->freelist_lock);
1550
1551                 bch2_open_bucket_put(c, ob);
1552         }
1553
1554         bch2_ec_stop_dev(c, ca);
1555
1556         /*
1557          * Wake up threads that were blocked on allocation, so they can notice
1558          * the device can no longer be removed and the capacity has changed:
1559          */
1560         closure_wake_up(&c->freelist_wait);
1561
1562         /*
1563          * journal_res_get() can block waiting for free space in the journal -
1564          * it needs to notice there may not be devices to allocate from anymore:
1565          */
1566         wake_up(&c->journal.wait);
1567
1568         /* Now wait for any in flight writes: */
1569
1570         closure_wait_event(&c->open_buckets_wait,
1571                            !bch2_dev_has_open_write_point(c, ca));
1572 }
1573
1574 /* device goes rw: */
1575 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1576 {
1577         unsigned i;
1578
1579         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1580                 if (ca->mi.data_allowed & (1 << i))
1581                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1582 }
1583
1584 void bch2_fs_allocator_background_init(struct bch_fs *c)
1585 {
1586         spin_lock_init(&c->freelist_lock);
1587         INIT_WORK(&c->discard_work, bch2_do_discards_work);
1588         INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1589 }