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