]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to f638850417 bcachefs: bch2_trans_log_msg()
[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 "btree_cache.h"
6 #include "btree_io.h"
7 #include "btree_key_cache.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "btree_gc.h"
11 #include "buckets.h"
12 #include "buckets_waiting_for_journal.h"
13 #include "clock.h"
14 #include "debug.h"
15 #include "ec.h"
16 #include "error.h"
17 #include "lru.h"
18 #include "recovery.h"
19 #include "varint.h"
20
21 #include <linux/kthread.h>
22 #include <linux/math64.h>
23 #include <linux/random.h>
24 #include <linux/rculist.h>
25 #include <linux/rcupdate.h>
26 #include <linux/sched/task.h>
27 #include <linux/sort.h>
28 #include <trace/events/bcachefs.h>
29
30 static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
31 #define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
32         BCH_ALLOC_FIELDS_V1()
33 #undef x
34 };
35
36 const char * const bch2_bucket_states[] = {
37         "free",
38         "need gc gens",
39         "need discard",
40         "cached",
41         "dirty",
42         NULL
43 };
44
45 /* Persistent alloc info: */
46
47 static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
48                                      const void **p, unsigned field)
49 {
50         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
51         u64 v;
52
53         if (!(a->fields & (1 << field)))
54                 return 0;
55
56         switch (bytes) {
57         case 1:
58                 v = *((const u8 *) *p);
59                 break;
60         case 2:
61                 v = le16_to_cpup(*p);
62                 break;
63         case 4:
64                 v = le32_to_cpup(*p);
65                 break;
66         case 8:
67                 v = le64_to_cpup(*p);
68                 break;
69         default:
70                 BUG();
71         }
72
73         *p += bytes;
74         return v;
75 }
76
77 static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
78                                       unsigned field, u64 v)
79 {
80         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
81
82         if (!v)
83                 return;
84
85         a->v.fields |= 1 << field;
86
87         switch (bytes) {
88         case 1:
89                 *((u8 *) *p) = v;
90                 break;
91         case 2:
92                 *((__le16 *) *p) = cpu_to_le16(v);
93                 break;
94         case 4:
95                 *((__le32 *) *p) = cpu_to_le32(v);
96                 break;
97         case 8:
98                 *((__le64 *) *p) = cpu_to_le64(v);
99                 break;
100         default:
101                 BUG();
102         }
103
104         *p += bytes;
105 }
106
107 static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
108                                  struct bkey_s_c k)
109 {
110         const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
111         const void *d = in->data;
112         unsigned idx = 0;
113
114         out->gen = in->gen;
115
116 #define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
117         BCH_ALLOC_FIELDS_V1()
118 #undef  x
119 }
120
121 static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
122                                 struct bkey_s_c k)
123 {
124         struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
125         const u8 *in = a.v->data;
126         const u8 *end = bkey_val_end(a);
127         unsigned fieldnr = 0;
128         int ret;
129         u64 v;
130
131         out->gen        = a.v->gen;
132         out->oldest_gen = a.v->oldest_gen;
133         out->data_type  = a.v->data_type;
134
135 #define x(_name, _bits)                                                 \
136         if (fieldnr < a.v->nr_fields) {                                 \
137                 ret = bch2_varint_decode_fast(in, end, &v);             \
138                 if (ret < 0)                                            \
139                         return ret;                                     \
140                 in += ret;                                              \
141         } else {                                                        \
142                 v = 0;                                                  \
143         }                                                               \
144         out->_name = v;                                                 \
145         if (v != out->_name)                                            \
146                 return -1;                                              \
147         fieldnr++;
148
149         BCH_ALLOC_FIELDS_V2()
150 #undef  x
151         return 0;
152 }
153
154 static int bch2_alloc_unpack_v3(struct bkey_alloc_unpacked *out,
155                                 struct bkey_s_c k)
156 {
157         struct bkey_s_c_alloc_v3 a = bkey_s_c_to_alloc_v3(k);
158         const u8 *in = a.v->data;
159         const u8 *end = bkey_val_end(a);
160         unsigned fieldnr = 0;
161         int ret;
162         u64 v;
163
164         out->gen        = a.v->gen;
165         out->oldest_gen = a.v->oldest_gen;
166         out->data_type  = a.v->data_type;
167         out->need_discard = BCH_ALLOC_NEED_DISCARD(a.v);
168         out->need_inc_gen = BCH_ALLOC_NEED_INC_GEN(a.v);
169         out->journal_seq = le64_to_cpu(a.v->journal_seq);
170
171 #define x(_name, _bits)                                                 \
172         if (fieldnr < a.v->nr_fields) {                                 \
173                 ret = bch2_varint_decode_fast(in, end, &v);             \
174                 if (ret < 0)                                            \
175                         return ret;                                     \
176                 in += ret;                                              \
177         } else {                                                        \
178                 v = 0;                                                  \
179         }                                                               \
180         out->_name = v;                                                 \
181         if (v != out->_name)                                            \
182                 return -1;                                              \
183         fieldnr++;
184
185         BCH_ALLOC_FIELDS_V2()
186 #undef  x
187         return 0;
188 }
189
190 static void bch2_alloc_pack_v3(struct bkey_alloc_buf *dst,
191                                const struct bkey_alloc_unpacked src)
192 {
193         struct bkey_i_alloc_v3 *a = bkey_alloc_v3_init(&dst->k);
194         unsigned nr_fields = 0, last_nonzero_fieldnr = 0;
195         u8 *out = a->v.data;
196         u8 *end = (void *) &dst[1];
197         u8 *last_nonzero_field = out;
198         unsigned bytes;
199
200         a->k.p          = POS(src.dev, src.bucket);
201         a->v.gen        = src.gen;
202         a->v.oldest_gen = src.oldest_gen;
203         a->v.data_type  = src.data_type;
204         a->v.journal_seq = cpu_to_le64(src.journal_seq);
205         SET_BCH_ALLOC_NEED_DISCARD(&a->v, src.need_discard);
206         SET_BCH_ALLOC_NEED_INC_GEN(&a->v, src.need_inc_gen);
207
208 #define x(_name, _bits)                                                 \
209         nr_fields++;                                                    \
210                                                                         \
211         if (src._name) {                                                \
212                 out += bch2_varint_encode_fast(out, src._name);         \
213                                                                         \
214                 last_nonzero_field = out;                               \
215                 last_nonzero_fieldnr = nr_fields;                       \
216         } else {                                                        \
217                 *out++ = 0;                                             \
218         }
219
220         BCH_ALLOC_FIELDS_V2()
221 #undef  x
222         BUG_ON(out > end);
223
224         out = last_nonzero_field;
225         a->v.nr_fields = last_nonzero_fieldnr;
226
227         bytes = (u8 *) out - (u8 *) &a->v;
228         set_bkey_val_bytes(&a->k, bytes);
229         memset_u64s_tail(&a->v, 0, bytes);
230 }
231
232 struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
233 {
234         struct bkey_alloc_unpacked ret = {
235                 .dev    = k.k->p.inode,
236                 .bucket = k.k->p.offset,
237                 .gen    = 0,
238         };
239
240         switch (k.k->type) {
241         case KEY_TYPE_alloc:
242                 bch2_alloc_unpack_v1(&ret, k);
243                 break;
244         case KEY_TYPE_alloc_v2:
245                 bch2_alloc_unpack_v2(&ret, k);
246                 break;
247         case KEY_TYPE_alloc_v3:
248                 bch2_alloc_unpack_v3(&ret, k);
249                 break;
250         }
251
252         return ret;
253 }
254
255 struct bkey_alloc_buf *bch2_alloc_pack(struct btree_trans *trans,
256                                        const struct bkey_alloc_unpacked src)
257 {
258         struct bkey_alloc_buf *dst;
259
260         dst = bch2_trans_kmalloc(trans, sizeof(struct bkey_alloc_buf));
261         if (!IS_ERR(dst))
262                 bch2_alloc_pack_v3(dst, src);
263
264         return dst;
265 }
266
267 int bch2_alloc_write(struct btree_trans *trans, struct btree_iter *iter,
268                      struct bkey_alloc_unpacked *u, unsigned trigger_flags)
269 {
270         struct bkey_alloc_buf *a = bch2_alloc_pack(trans, *u);
271
272         return PTR_ERR_OR_ZERO(a) ?:
273                 bch2_trans_update(trans, iter, &a->k, trigger_flags);
274 }
275
276 static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
277 {
278         unsigned i, bytes = offsetof(struct bch_alloc, data);
279
280         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
281                 if (a->fields & (1 << i))
282                         bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
283
284         return DIV_ROUND_UP(bytes, sizeof(u64));
285 }
286
287 const char *bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k)
288 {
289         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
290
291         if (k.k->p.inode >= c->sb.nr_devices ||
292             !c->devs[k.k->p.inode])
293                 return "invalid device";
294
295         /* allow for unknown fields */
296         if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v))
297                 return "incorrect value size";
298
299         return NULL;
300 }
301
302 const char *bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k)
303 {
304         struct bkey_alloc_unpacked u;
305
306         if (k.k->p.inode >= c->sb.nr_devices ||
307             !c->devs[k.k->p.inode])
308                 return "invalid device";
309
310         if (bch2_alloc_unpack_v2(&u, k))
311                 return "unpack error";
312
313         return NULL;
314 }
315
316 const char *bch2_alloc_v3_invalid(const struct bch_fs *c, struct bkey_s_c k)
317 {
318         struct bkey_alloc_unpacked u;
319
320         if (k.k->p.inode >= c->sb.nr_devices ||
321             !c->devs[k.k->p.inode])
322                 return "invalid device";
323
324         if (bch2_alloc_unpack_v3(&u, k))
325                 return "unpack error";
326
327         return NULL;
328 }
329
330 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
331                            struct bkey_s_c k)
332 {
333         struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);
334
335         pr_buf(out, "gen %u oldest_gen %u data_type %s journal_seq %llu need_discard %u",
336                u.gen, u.oldest_gen, bch2_data_types[u.data_type],
337                u.journal_seq, u.need_discard);
338 #define x(_name, ...)   pr_buf(out, " " #_name " %llu", (u64) u._name);
339         BCH_ALLOC_FIELDS_V2()
340 #undef  x
341 }
342
343 int bch2_alloc_read(struct bch_fs *c)
344 {
345         struct btree_trans trans;
346         struct btree_iter iter;
347         struct bkey_s_c k;
348         struct bch_dev *ca;
349         int ret;
350
351         bch2_trans_init(&trans, c, 0, 0);
352
353         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
354                            BTREE_ITER_PREFETCH, k, ret) {
355                 ca = bch_dev_bkey_exists(c, k.k->p.inode);
356
357                 *bucket_gen(ca, k.k->p.offset) = bch2_alloc_unpack(k).gen;
358         }
359         bch2_trans_iter_exit(&trans, &iter);
360
361         bch2_trans_exit(&trans);
362
363         if (ret)
364                 bch_err(c, "error reading alloc info: %i", ret);
365
366         return ret;
367 }
368
369 /* Free space/discard btree: */
370
371 static int bch2_bucket_do_index(struct btree_trans *trans,
372                                 struct bkey_s_c alloc_k,
373                                 struct bkey_alloc_unpacked a,
374                                 bool set)
375 {
376         struct bch_fs *c = trans->c;
377         struct bch_dev *ca = bch_dev_bkey_exists(c, a.dev);
378         struct btree_iter iter;
379         struct bkey_s_c old;
380         struct bkey_i *k;
381         enum bucket_state state = bucket_state(a);
382         enum btree_id btree;
383         enum bch_bkey_type old_type = !set ? KEY_TYPE_set : KEY_TYPE_deleted;
384         enum bch_bkey_type new_type =  set ? KEY_TYPE_set : KEY_TYPE_deleted;
385         struct printbuf buf = PRINTBUF;
386         int ret;
387
388         if (state != BUCKET_free &&
389             state != BUCKET_need_discard)
390                 return 0;
391
392         k = bch2_trans_kmalloc(trans, sizeof(*k));
393         if (IS_ERR(k))
394                 return PTR_ERR(k);
395
396         bkey_init(&k->k);
397         k->k.type = new_type;
398
399         switch (state) {
400         case BUCKET_free:
401                 btree = BTREE_ID_freespace;
402                 k->k.p = alloc_freespace_pos(a);
403                 bch2_key_resize(&k->k, 1);
404                 break;
405         case BUCKET_need_discard:
406                 btree = BTREE_ID_need_discard;
407                 k->k.p = POS(a.dev, a.bucket);
408                 break;
409         default:
410                 return 0;
411         }
412
413         bch2_trans_iter_init(trans, &iter, btree,
414                              bkey_start_pos(&k->k),
415                              BTREE_ITER_INTENT);
416         old = bch2_btree_iter_peek_slot(&iter);
417         ret = bkey_err(old);
418         if (ret)
419                 goto err;
420
421         if (ca->mi.freespace_initialized &&
422             bch2_fs_inconsistent_on(old.k->type != old_type, c,
423                         "incorrect key when %s %s btree (got %s should be %s)\n"
424                         "  for %s",
425                         set ? "setting" : "clearing",
426                         bch2_btree_ids[btree],
427                         bch2_bkey_types[old.k->type],
428                         bch2_bkey_types[old_type],
429                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
430                 ret = -EIO;
431                 goto err;
432         }
433
434         ret = bch2_trans_update(trans, &iter, k, 0);
435 err:
436         bch2_trans_iter_exit(trans, &iter);
437         printbuf_exit(&buf);
438         return ret;
439 }
440
441 int bch2_trans_mark_alloc(struct btree_trans *trans,
442                           struct bkey_s_c old, struct bkey_i *new,
443                           unsigned flags)
444 {
445         struct bch_fs *c = trans->c;
446         struct bkey_alloc_unpacked old_u = bch2_alloc_unpack(old);
447         struct bkey_alloc_unpacked new_u = bch2_alloc_unpack(bkey_i_to_s_c(new));
448         u64 old_lru, new_lru;
449         bool need_repack = false;
450         int ret = 0;
451
452         if (new_u.dirty_sectors > old_u.dirty_sectors ||
453             new_u.cached_sectors > old_u.cached_sectors) {
454                 new_u.read_time = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
455                 new_u.write_time = max_t(u64, 1, atomic64_read(&c->io_clock[WRITE].now));
456                 new_u.need_inc_gen = true;
457                 new_u.need_discard = true;
458                 need_repack = true;
459         }
460
461         if (old_u.data_type && !new_u.data_type &&
462             old_u.gen == new_u.gen &&
463             !bch2_bucket_is_open_safe(c, new->k.p.inode, new->k.p.offset)) {
464                 new_u.gen++;
465                 new_u.need_inc_gen = false;
466                 need_repack = true;
467         }
468
469         if (bucket_state(old_u) != bucket_state(new_u) ||
470             (bucket_state(new_u) == BUCKET_free &&
471              alloc_freespace_genbits(old_u) != alloc_freespace_genbits(new_u))) {
472                 ret =   bch2_bucket_do_index(trans, old, old_u, false) ?:
473                         bch2_bucket_do_index(trans, bkey_i_to_s_c(new), new_u, true);
474                 if (ret)
475                         return ret;
476         }
477
478         old_lru = alloc_lru_idx(old_u);
479         new_lru = alloc_lru_idx(new_u);
480
481         if (old_lru != new_lru) {
482                 ret = bch2_lru_change(trans, new->k.p.inode, new->k.p.offset,
483                                       old_lru, &new_lru);
484                 if (ret)
485                         return ret;
486
487                 if (new_lru && new_u.read_time != new_lru) {
488                         new_u.read_time = new_lru;
489                         need_repack = true;
490                 }
491         }
492
493         if (need_repack && !bkey_deleted(&new->k))
494                 bch2_alloc_pack_v3((void *) new, new_u);
495
496         return 0;
497 }
498
499 static int bch2_check_alloc_key(struct btree_trans *trans,
500                                 struct btree_iter *alloc_iter)
501 {
502         struct bch_fs *c = trans->c;
503         struct btree_iter discard_iter, freespace_iter, lru_iter;
504         struct bkey_alloc_unpacked a;
505         unsigned discard_key_type, freespace_key_type;
506         struct bkey_s_c alloc_k, k;
507         struct printbuf buf = PRINTBUF;
508         struct printbuf buf2 = PRINTBUF;
509         int ret;
510
511         alloc_k = bch2_btree_iter_peek(alloc_iter);
512         if (!alloc_k.k)
513                 return 0;
514
515         ret = bkey_err(alloc_k);
516         if (ret)
517                 return ret;
518
519         a = bch2_alloc_unpack(alloc_k);
520         discard_key_type = bucket_state(a) == BUCKET_need_discard
521                 ? KEY_TYPE_set : 0;
522         freespace_key_type = bucket_state(a) == BUCKET_free
523                 ? KEY_TYPE_set : 0;
524
525         bch2_trans_iter_init(trans, &discard_iter, BTREE_ID_need_discard,
526                              alloc_k.k->p, 0);
527         bch2_trans_iter_init(trans, &freespace_iter, BTREE_ID_freespace,
528                              alloc_freespace_pos(a), 0);
529         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
530                              POS(a.dev, a.read_time), 0);
531
532         k = bch2_btree_iter_peek_slot(&discard_iter);
533         ret = bkey_err(k);
534         if (ret)
535                 goto err;
536
537         if (fsck_err_on(k.k->type != discard_key_type, c,
538                         "incorrect key in need_discard btree (got %s should be %s)\n"
539                         "  %s",
540                         bch2_bkey_types[k.k->type],
541                         bch2_bkey_types[discard_key_type],
542                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
543                 struct bkey_i *update =
544                         bch2_trans_kmalloc(trans, sizeof(*update));
545
546                 ret = PTR_ERR_OR_ZERO(update);
547                 if (ret)
548                         goto err;
549
550                 bkey_init(&update->k);
551                 update->k.type  = discard_key_type;
552                 update->k.p     = discard_iter.pos;
553
554                 ret =   bch2_trans_update(trans, &discard_iter, update, 0) ?:
555                         bch2_trans_commit(trans, NULL, NULL, 0);
556                 if (ret)
557                         goto err;
558         }
559
560         k = bch2_btree_iter_peek_slot(&freespace_iter);
561         ret = bkey_err(k);
562         if (ret)
563                 goto err;
564
565         if (fsck_err_on(k.k->type != freespace_key_type, c,
566                         "incorrect key in freespace btree (got %s should be %s)\n"
567                         "  %s",
568                         bch2_bkey_types[k.k->type],
569                         bch2_bkey_types[freespace_key_type],
570                         (printbuf_reset(&buf),
571                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
572                 struct bkey_i *update =
573                         bch2_trans_kmalloc(trans, sizeof(*update));
574
575                 ret = PTR_ERR_OR_ZERO(update);
576                 if (ret)
577                         goto err;
578
579                 bkey_init(&update->k);
580                 update->k.type  = freespace_key_type;
581                 update->k.p     = freespace_iter.pos;
582                 bch2_key_resize(&update->k, 1);
583
584                 ret   = bch2_trans_update(trans, &freespace_iter, update, 0) ?:
585                         bch2_trans_commit(trans, NULL, NULL, 0);
586                 if (ret)
587                         goto err;
588         }
589
590         if (bucket_state(a) == BUCKET_cached) {
591                 if (fsck_err_on(!a.read_time, c,
592                                 "cached bucket with read_time 0\n"
593                                 "  %s",
594                         (printbuf_reset(&buf),
595                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
596
597                         a.read_time = atomic64_read(&c->io_clock[READ].now);
598
599                         ret   = bch2_lru_change(trans, a.dev, a.bucket,
600                                                 0, &a.read_time) ?:
601                                 bch2_alloc_write(trans, alloc_iter, &a, BTREE_TRIGGER_NORUN);
602                                 bch2_trans_commit(trans, NULL, NULL, 0);
603                         if (ret)
604                                 goto err;
605                 }
606
607                 k = bch2_btree_iter_peek_slot(&lru_iter);
608                 ret = bkey_err(k);
609                 if (ret)
610                         goto err;
611
612                 if (fsck_err_on(k.k->type != KEY_TYPE_lru ||
613                                 le64_to_cpu(bkey_s_c_to_lru(k).v->idx) != a.bucket, c,
614                         "incorrect/missing lru entry\n"
615                         "  %s\n"
616                         "  %s",
617                         (printbuf_reset(&buf),
618                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
619                         (bch2_bkey_val_to_text(&buf2, c, k), buf2.buf))) {
620                         u64 read_time = a.read_time;
621
622                         ret   = bch2_lru_change(trans, a.dev, a.bucket,
623                                                 0, &a.read_time) ?:
624                                 (a.read_time != read_time
625                                  ? bch2_alloc_write(trans, alloc_iter, &a, BTREE_TRIGGER_NORUN)
626                                  : 0) ?:
627                                 bch2_trans_commit(trans, NULL, NULL, 0);
628                         if (ret)
629                                 goto err;
630                 }
631         }
632 err:
633 fsck_err:
634         bch2_trans_iter_exit(trans, &lru_iter);
635         bch2_trans_iter_exit(trans, &freespace_iter);
636         bch2_trans_iter_exit(trans, &discard_iter);
637         printbuf_exit(&buf2);
638         printbuf_exit(&buf);
639         return ret;
640 }
641
642 static inline bool bch2_dev_bucket_exists(struct bch_fs *c, struct bpos pos)
643 {
644         struct bch_dev *ca;
645
646         if (pos.inode >= c->sb.nr_devices || !c->devs[pos.inode])
647                 return false;
648
649         ca = bch_dev_bkey_exists(c, pos.inode);
650         return pos.offset >= ca->mi.first_bucket &&
651                 pos.offset < ca->mi.nbuckets;
652 }
653
654 static int bch2_check_freespace_key(struct btree_trans *trans,
655                                     struct btree_iter *freespace_iter,
656                                     bool initial)
657 {
658         struct bch_fs *c = trans->c;
659         struct btree_iter alloc_iter;
660         struct bkey_s_c k, freespace_k;
661         struct bkey_alloc_unpacked a;
662         u64 genbits;
663         struct bpos pos;
664         struct bkey_i *update;
665         struct printbuf buf = PRINTBUF;
666         int ret;
667
668         freespace_k = bch2_btree_iter_peek(freespace_iter);
669         if (!freespace_k.k)
670                 return 1;
671
672         ret = bkey_err(freespace_k);
673         if (ret)
674                 return ret;
675
676         pos = freespace_iter->pos;
677         pos.offset &= ~(~0ULL << 56);
678         genbits = freespace_iter->pos.offset & (~0ULL << 56);
679
680         bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc, pos, 0);
681
682         if (fsck_err_on(!bch2_dev_bucket_exists(c, pos), c,
683                         "%llu:%llu set in freespace btree but device or bucket does not exist",
684                         pos.inode, pos.offset))
685                 goto delete;
686
687         k = bch2_btree_iter_peek_slot(&alloc_iter);
688         ret = bkey_err(k);
689         if (ret)
690                 goto err;
691
692         a = bch2_alloc_unpack(k);
693
694         if (fsck_err_on(bucket_state(a) != BUCKET_free ||
695                         genbits != alloc_freespace_genbits(a), c,
696                         "%s\n  incorrectly set in freespace index (free %u, genbits %llu should be %llu)",
697                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf),
698                         bucket_state(a) == BUCKET_free,
699                         genbits >> 56, alloc_freespace_genbits(a) >> 56))
700                 goto delete;
701 out:
702 err:
703 fsck_err:
704         bch2_trans_iter_exit(trans, &alloc_iter);
705         printbuf_exit(&buf);
706         return ret;
707 delete:
708         update = bch2_trans_kmalloc(trans, sizeof(*update));
709         ret = PTR_ERR_OR_ZERO(update);
710         if (ret)
711                 goto err;
712
713         bkey_init(&update->k);
714         update->k.p = freespace_iter->pos;
715         bch2_key_resize(&update->k, 1);
716
717         ret   = bch2_trans_update(trans, freespace_iter, update, 0) ?:
718                 bch2_trans_commit(trans, NULL, NULL, 0);
719         goto out;
720 }
721
722 int bch2_check_alloc_info(struct bch_fs *c, bool initial)
723 {
724         struct btree_trans trans;
725         struct btree_iter iter;
726         struct bkey_s_c k;
727         int ret = 0, last_dev = -1;
728
729         bch2_trans_init(&trans, c, 0, 0);
730
731         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
732                            BTREE_ITER_PREFETCH, k, ret) {
733                 if (k.k->p.inode != last_dev) {
734                         struct bch_dev *ca = bch_dev_bkey_exists(c, k.k->p.inode);
735
736                         if (!ca->mi.freespace_initialized) {
737                                 bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
738                                 continue;
739                         }
740
741                         last_dev = k.k->p.inode;
742                 }
743
744                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
745                         bch2_check_alloc_key(&trans, &iter));
746                 if (ret)
747                         break;
748         }
749         bch2_trans_iter_exit(&trans, &iter);
750
751         if (ret)
752                 goto err;
753
754         bch2_trans_iter_init(&trans, &iter, BTREE_ID_freespace, POS_MIN,
755                              BTREE_ITER_PREFETCH);
756         while (1) {
757                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
758                         bch2_check_freespace_key(&trans, &iter, initial));
759                 if (ret)
760                         break;
761
762                 bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
763         }
764         bch2_trans_iter_exit(&trans, &iter);
765 err:
766         bch2_trans_exit(&trans);
767         return ret < 0 ? ret : 0;
768 }
769
770 static int bch2_clear_need_discard(struct btree_trans *trans, struct bpos pos,
771                                    struct bch_dev *ca, bool *discard_done)
772 {
773         struct bch_fs *c = trans->c;
774         struct btree_iter iter;
775         struct bkey_s_c k;
776         struct bkey_alloc_unpacked a;
777         struct printbuf buf = PRINTBUF;
778         int ret;
779
780         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, pos,
781                              BTREE_ITER_CACHED);
782         k = bch2_btree_iter_peek_slot(&iter);
783         ret = bkey_err(k);
784         if (ret)
785                 goto out;
786
787         a = bch2_alloc_unpack(k);
788
789         if (a.need_inc_gen) {
790                 a.gen++;
791                 a.need_inc_gen = false;
792                 goto write;
793         }
794
795         BUG_ON(a.journal_seq > c->journal.flushed_seq_ondisk);
796
797         if (bch2_fs_inconsistent_on(!a.need_discard, c,
798                         "%s\n  incorrectly set in need_discard btree",
799                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
800                 ret = -EIO;
801                 goto out;
802         }
803
804         if (!*discard_done && ca->mi.discard && !c->opts.nochanges) {
805                 /*
806                  * This works without any other locks because this is the only
807                  * thread that removes items from the need_discard tree
808                  */
809                 bch2_trans_unlock(trans);
810                 blkdev_issue_discard(ca->disk_sb.bdev,
811                                      k.k->p.offset * ca->mi.bucket_size,
812                                      ca->mi.bucket_size,
813                                      GFP_KERNEL, 0);
814                 *discard_done = true;
815
816                 ret = bch2_trans_relock(trans);
817                 if (ret)
818                         goto out;
819         }
820
821         a.need_discard = false;
822 write:
823         ret = bch2_alloc_write(trans, &iter, &a, 0);
824 out:
825         bch2_trans_iter_exit(trans, &iter);
826         printbuf_exit(&buf);
827         return ret;
828 }
829
830 static void bch2_do_discards_work(struct work_struct *work)
831 {
832         struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
833         struct bch_dev *ca = NULL;
834         struct btree_trans trans;
835         struct btree_iter iter;
836         struct bkey_s_c k;
837         int ret;
838
839         bch2_trans_init(&trans, c, 0, 0);
840
841         for_each_btree_key(&trans, iter, BTREE_ID_need_discard,
842                            POS_MIN, 0, k, ret) {
843                 bool discard_done = false;
844
845                 if (ca && k.k->p.inode != ca->dev_idx) {
846                         percpu_ref_put(&ca->io_ref);
847                         ca = NULL;
848                 }
849
850                 if (!ca) {
851                         ca = bch_dev_bkey_exists(c, k.k->p.inode);
852                         if (!percpu_ref_tryget(&ca->io_ref)) {
853                                 ca = NULL;
854                                 bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
855                                 continue;
856                         }
857                 }
858
859                 if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
860                                 c->journal.flushed_seq_ondisk,
861                                 k.k->p.inode, k.k->p.offset) ||
862                     bch2_bucket_is_open_safe(c, k.k->p.inode, k.k->p.offset))
863                         continue;
864
865                 ret = __bch2_trans_do(&trans, NULL, NULL,
866                                       BTREE_INSERT_USE_RESERVE|
867                                       BTREE_INSERT_NOFAIL,
868                                 bch2_clear_need_discard(&trans, k.k->p, ca, &discard_done));
869                 if (ret)
870                         break;
871         }
872         bch2_trans_iter_exit(&trans, &iter);
873
874         if (ca)
875                 percpu_ref_put(&ca->io_ref);
876
877         bch2_trans_exit(&trans);
878         percpu_ref_put(&c->writes);
879 }
880
881 void bch2_do_discards(struct bch_fs *c)
882 {
883         if (percpu_ref_tryget(&c->writes) &&
884             !queue_work(system_long_wq, &c->discard_work))
885                 percpu_ref_put(&c->writes);
886 }
887
888 static int invalidate_one_bucket(struct btree_trans *trans, struct bch_dev *ca)
889 {
890         struct bch_fs *c = trans->c;
891         struct btree_iter lru_iter, alloc_iter = { NULL };
892         struct bkey_s_c k;
893         struct bkey_alloc_unpacked a;
894         u64 bucket, idx;
895         int ret;
896
897         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
898                              POS(ca->dev_idx, 0), 0);
899         k = bch2_btree_iter_peek(&lru_iter);
900         ret = bkey_err(k);
901         if (ret)
902                 goto out;
903
904         if (!k.k || k.k->p.inode != ca->dev_idx)
905                 goto out;
906
907         if (bch2_fs_inconsistent_on(k.k->type != KEY_TYPE_lru, c,
908                                     "non lru key in lru btree"))
909                 goto out;
910
911         idx     = k.k->p.offset;
912         bucket  = le64_to_cpu(bkey_s_c_to_lru(k).v->idx);
913
914         bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc,
915                              POS(ca->dev_idx, bucket),
916                              BTREE_ITER_CACHED|
917                              BTREE_ITER_INTENT);
918         k = bch2_btree_iter_peek_slot(&alloc_iter);
919         ret = bkey_err(k);
920         if (ret)
921                 goto out;
922
923         a = bch2_alloc_unpack(k);
924
925         if (bch2_fs_inconsistent_on(idx != alloc_lru_idx(a), c,
926                         "invalidating bucket with wrong lru idx (got %llu should be %llu",
927                         idx, alloc_lru_idx(a)))
928                 goto out;
929
930         a.gen++;
931         a.need_inc_gen          = false;
932         a.data_type             = 0;
933         a.dirty_sectors         = 0;
934         a.cached_sectors        = 0;
935         a.read_time             = atomic64_read(&c->io_clock[READ].now);
936         a.write_time            = atomic64_read(&c->io_clock[WRITE].now);
937
938         ret = bch2_alloc_write(trans, &alloc_iter, &a,
939                                BTREE_TRIGGER_BUCKET_INVALIDATE);
940 out:
941         bch2_trans_iter_exit(trans, &alloc_iter);
942         bch2_trans_iter_exit(trans, &lru_iter);
943         return ret;
944 }
945
946 static void bch2_do_invalidates_work(struct work_struct *work)
947 {
948         struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
949         struct bch_dev *ca;
950         struct btree_trans trans;
951         unsigned i;
952         int ret = 0;
953
954         bch2_trans_init(&trans, c, 0, 0);
955
956         for_each_member_device(ca, c, i)
957                 while (!ret && should_invalidate_buckets(ca))
958                         ret = __bch2_trans_do(&trans, NULL, NULL,
959                                               BTREE_INSERT_USE_RESERVE|
960                                               BTREE_INSERT_NOFAIL,
961                                         invalidate_one_bucket(&trans, ca));
962
963         bch2_trans_exit(&trans);
964         percpu_ref_put(&c->writes);
965 }
966
967 void bch2_do_invalidates(struct bch_fs *c)
968 {
969         if (percpu_ref_tryget(&c->writes))
970                 queue_work(system_long_wq, &c->invalidate_work);
971 }
972
973 static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
974 {
975         struct btree_trans trans;
976         struct btree_iter iter;
977         struct bkey_s_c k;
978         struct bkey_alloc_unpacked a;
979         struct bch_member *m;
980         int ret;
981
982         bch2_trans_init(&trans, c, 0, 0);
983
984         for_each_btree_key(&trans, iter, BTREE_ID_alloc,
985                            POS(ca->dev_idx, ca->mi.first_bucket),
986                            BTREE_ITER_SLOTS|
987                            BTREE_ITER_PREFETCH, k, ret) {
988                 if (iter.pos.offset >= ca->mi.nbuckets)
989                         break;
990
991                 a = bch2_alloc_unpack(k);
992                 ret = __bch2_trans_do(&trans, NULL, NULL,
993                                       BTREE_INSERT_LAZY_RW,
994                                  bch2_bucket_do_index(&trans, k, a, true));
995                 if (ret)
996                         break;
997         }
998         bch2_trans_iter_exit(&trans, &iter);
999
1000         bch2_trans_exit(&trans);
1001
1002         if (ret) {
1003                 bch_err(ca, "error initializing free space: %i", ret);
1004                 return ret;
1005         }
1006
1007         mutex_lock(&c->sb_lock);
1008         m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
1009         SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
1010         mutex_unlock(&c->sb_lock);
1011
1012         return ret;
1013 }
1014
1015 int bch2_fs_freespace_init(struct bch_fs *c)
1016 {
1017         struct bch_dev *ca;
1018         unsigned i;
1019         int ret = 0;
1020         bool doing_init = false;
1021
1022         /*
1023          * We can crash during the device add path, so we need to check this on
1024          * every mount:
1025          */
1026
1027         for_each_member_device(ca, c, i) {
1028                 if (ca->mi.freespace_initialized)
1029                         continue;
1030
1031                 if (!doing_init) {
1032                         bch_info(c, "initializing freespace");
1033                         doing_init = true;
1034                 }
1035
1036                 ret = bch2_dev_freespace_init(c, ca);
1037                 if (ret) {
1038                         percpu_ref_put(&ca->ref);
1039                         return ret;
1040                 }
1041         }
1042
1043         if (doing_init) {
1044                 mutex_lock(&c->sb_lock);
1045                 bch2_write_super(c);
1046                 mutex_unlock(&c->sb_lock);
1047
1048                 bch_verbose(c, "done initializing freespace");
1049         }
1050
1051         return ret;
1052 }
1053
1054 /* Bucket IO clocks: */
1055
1056 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
1057                               size_t bucket_nr, int rw)
1058 {
1059         struct bch_fs *c = trans->c;
1060         struct btree_iter iter;
1061         struct bkey_s_c k;
1062         struct bkey_alloc_unpacked u;
1063         u64 *time, now;
1064         int ret = 0;
1065
1066         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, POS(dev, bucket_nr),
1067                              BTREE_ITER_CACHED|
1068                              BTREE_ITER_INTENT);
1069         k = bch2_btree_iter_peek_slot(&iter);
1070         ret = bkey_err(k);
1071         if (ret)
1072                 goto out;
1073
1074         u = bch2_alloc_unpack(k);
1075
1076         time = rw == READ ? &u.read_time : &u.write_time;
1077         now = atomic64_read(&c->io_clock[rw].now);
1078         if (*time == now)
1079                 goto out;
1080
1081         *time = now;
1082
1083         ret   = bch2_alloc_write(trans, &iter, &u, 0) ?:
1084                 bch2_trans_commit(trans, NULL, NULL, 0);
1085 out:
1086         bch2_trans_iter_exit(trans, &iter);
1087         return ret;
1088 }
1089
1090 /* Startup/shutdown (ro/rw): */
1091
1092 void bch2_recalc_capacity(struct bch_fs *c)
1093 {
1094         struct bch_dev *ca;
1095         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1096         unsigned bucket_size_max = 0;
1097         unsigned long ra_pages = 0;
1098         unsigned i;
1099
1100         lockdep_assert_held(&c->state_lock);
1101
1102         for_each_online_member(ca, c, i) {
1103                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
1104
1105                 ra_pages += bdi->ra_pages;
1106         }
1107
1108         bch2_set_ra_pages(c, ra_pages);
1109
1110         for_each_rw_member(ca, c, i) {
1111                 u64 dev_reserve = 0;
1112
1113                 /*
1114                  * We need to reserve buckets (from the number
1115                  * of currently available buckets) against
1116                  * foreground writes so that mainly copygc can
1117                  * make forward progress.
1118                  *
1119                  * We need enough to refill the various reserves
1120                  * from scratch - copygc will use its entire
1121                  * reserve all at once, then run against when
1122                  * its reserve is refilled (from the formerly
1123                  * available buckets).
1124                  *
1125                  * This reserve is just used when considering if
1126                  * allocations for foreground writes must wait -
1127                  * not -ENOSPC calculations.
1128                  */
1129
1130                 dev_reserve += ca->nr_btree_reserve * 2;
1131                 dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1132
1133                 dev_reserve += 1;       /* btree write point */
1134                 dev_reserve += 1;       /* copygc write point */
1135                 dev_reserve += 1;       /* rebalance write point */
1136
1137                 dev_reserve *= ca->mi.bucket_size;
1138
1139                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1140                                              ca->mi.first_bucket);
1141
1142                 reserved_sectors += dev_reserve * 2;
1143
1144                 bucket_size_max = max_t(unsigned, bucket_size_max,
1145                                         ca->mi.bucket_size);
1146         }
1147
1148         gc_reserve = c->opts.gc_reserve_bytes
1149                 ? c->opts.gc_reserve_bytes >> 9
1150                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1151
1152         reserved_sectors = max(gc_reserve, reserved_sectors);
1153
1154         reserved_sectors = min(reserved_sectors, capacity);
1155
1156         c->capacity = capacity - reserved_sectors;
1157
1158         c->bucket_size_max = bucket_size_max;
1159
1160         /* Wake up case someone was waiting for buckets */
1161         closure_wake_up(&c->freelist_wait);
1162 }
1163
1164 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1165 {
1166         struct open_bucket *ob;
1167         bool ret = false;
1168
1169         for (ob = c->open_buckets;
1170              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1171              ob++) {
1172                 spin_lock(&ob->lock);
1173                 if (ob->valid && !ob->on_partial_list &&
1174                     ob->dev == ca->dev_idx)
1175                         ret = true;
1176                 spin_unlock(&ob->lock);
1177         }
1178
1179         return ret;
1180 }
1181
1182 /* device goes ro: */
1183 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1184 {
1185         unsigned i;
1186
1187         /* First, remove device from allocation groups: */
1188
1189         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1190                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1191
1192         /*
1193          * Capacity is calculated based off of devices in allocation groups:
1194          */
1195         bch2_recalc_capacity(c);
1196
1197         /* Next, close write points that point to this device... */
1198         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1199                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1200
1201         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1202         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1203         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1204
1205         mutex_lock(&c->btree_reserve_cache_lock);
1206         while (c->btree_reserve_cache_nr) {
1207                 struct btree_alloc *a =
1208                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1209
1210                 bch2_open_buckets_put(c, &a->ob);
1211         }
1212         mutex_unlock(&c->btree_reserve_cache_lock);
1213
1214         while (1) {
1215                 struct open_bucket *ob;
1216
1217                 spin_lock(&c->freelist_lock);
1218                 if (!ca->open_buckets_partial_nr) {
1219                         spin_unlock(&c->freelist_lock);
1220                         break;
1221                 }
1222                 ob = c->open_buckets +
1223                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1224                 ob->on_partial_list = false;
1225                 spin_unlock(&c->freelist_lock);
1226
1227                 bch2_open_bucket_put(c, ob);
1228         }
1229
1230         bch2_ec_stop_dev(c, ca);
1231
1232         /*
1233          * Wake up threads that were blocked on allocation, so they can notice
1234          * the device can no longer be removed and the capacity has changed:
1235          */
1236         closure_wake_up(&c->freelist_wait);
1237
1238         /*
1239          * journal_res_get() can block waiting for free space in the journal -
1240          * it needs to notice there may not be devices to allocate from anymore:
1241          */
1242         wake_up(&c->journal.wait);
1243
1244         /* Now wait for any in flight writes: */
1245
1246         closure_wait_event(&c->open_buckets_wait,
1247                            !bch2_dev_has_open_write_point(c, ca));
1248 }
1249
1250 /* device goes rw: */
1251 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1252 {
1253         unsigned i;
1254
1255         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1256                 if (ca->mi.data_allowed & (1 << i))
1257                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1258 }
1259
1260 void bch2_fs_allocator_background_init(struct bch_fs *c)
1261 {
1262         spin_lock_init(&c->freelist_lock);
1263         INIT_WORK(&c->discard_work, bch2_do_discards_work);
1264         INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1265 }