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